diff --git a/dev-support/checkstyle-suppressions.xml b/dev-support/checkstyle-suppressions.xml
index 9856e3ca8c..624016707b 100644
--- a/dev-support/checkstyle-suppressions.xml
+++ b/dev-support/checkstyle-suppressions.xml
@@ -28,13 +28,18 @@
+
+
+
+
+
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/AssetMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/AssetMgr.java
index bdaeee671a..4d55598883 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/AssetMgr.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/AssetMgr.java
@@ -99,47 +99,68 @@ public class AssetMgr extends AssetMgrBase {
private static final String PROP_RANGER_LOG_SC_NOT_MODIFIED = "ranger.log.SC_NOT_MODIFIED";
private static final String PROP_PLUGIN_ACTIVITY_AUDIT_NOT_MODIFIED = "ranger.plugin.activity.audit.not.modified";
private static final String PROP_PLUGIN_ACTIVITY_AUDIT_COMMIT_INLINE = "ranger.plugin.activity.audit.commit.inline";
- private static final String adminCapabilities = Long.toHexString(new RangerPluginCapability().getPluginCapabilities());
+ private static final String adminCapabilities = Long.toHexString(new RangerPluginCapability().getPluginCapabilities());
+
@Autowired
- XPermMapService xPermMapService;
+ XPermMapService xPermMapService;
+
@Autowired
- XAuditMapService xAuditMapService;
+ XAuditMapService xAuditMapService;
+
@Autowired
- JSONUtil jsonUtil;
+ JSONUtil jsonUtil;
+
@Autowired
- RangerBizUtil msBizUtil;
+ RangerBizUtil msBizUtil;
+
@Autowired
- StringUtil stringUtil;
+ StringUtil stringUtil;
+
@Autowired
- RangerDaoManager rangerDaoManager;
+ RangerDaoManager rangerDaoManager;
+
@Autowired
- XUserService xUserService;
+ XUserService xUserService;
+
@Autowired
- RangerBizUtil xaBizUtil;
+ RangerBizUtil xaBizUtil;
+
@Autowired
- RangerTrxLogV2Service xTrxLogService;
+ RangerTrxLogV2Service xTrxLogService;
+
@Autowired
- XAccessAuditService xAccessAuditService;
+ XAccessAuditService xAccessAuditService;
+
@Autowired
- XGroupService xGroupService;
+ XGroupService xGroupService;
+
@Autowired
- XUserMgr xUserMgr;
+ XUserMgr xUserMgr;
+
@Autowired
- SolrAccessAuditsService solrAccessAuditsService;
+ SolrAccessAuditsService solrAccessAuditsService;
+
@Autowired
- ElasticSearchAccessAuditsService elasticSearchAccessAuditsService;
+ ElasticSearchAccessAuditsService elasticSearchAccessAuditsService;
+
@Autowired
- CloudWatchAccessAuditsService cloudWatchAccessAuditsService;
+ CloudWatchAccessAuditsService cloudWatchAccessAuditsService;
+
@Autowired
- XPolicyService xPolicyService;
+ XPolicyService xPolicyService;
+
@Autowired
RangerTransactionSynchronizationAdapter transactionSynchronizationAdapter;
+
@Autowired
- RangerPluginInfoService pluginInfoService;
+ RangerPluginInfoService pluginInfoService;
+
@Autowired
- XUgsyncAuditInfoService xUgsyncAuditInfoService;
+ XUgsyncAuditInfoService xUgsyncAuditInfoService;
+
@Autowired
- ServiceMgr serviceMgr;
+ ServiceMgr serviceMgr;
+
boolean rangerLogNotModified;
boolean pluginActivityAuditLogNotModified;
boolean pluginActivityAuditCommitInline;
@@ -162,21 +183,28 @@ public void init() {
public String getLatestRepoPolicy(VXAsset xAsset, List xResourceList, Long updatedTime, X509Certificate[] certchain, boolean httpEnabled, String epoch, String ipAddress, boolean isSecure, String count, String agentId) {
if (xAsset == null) {
logger.error("Requested repository not found");
+
throw restErrorUtil.createRESTException("No Data Found.", MessageEnums.DATA_NOT_FOUND);
}
+
if (xResourceList == null) {
logger.error("ResourceList is found");
+
throw restErrorUtil.createRESTException("No Data Found.", MessageEnums.DATA_NOT_FOUND);
}
+
if (xAsset.getActiveStatus() == RangerCommonEnums.ACT_STATUS_DISABLED) {
logger.error("Requested repository is disabled");
+
throw restErrorUtil.createRESTException("Unauthorized access.", MessageEnums.OPER_NO_EXPORT);
}
HashMap updatedRepo = new HashMap<>();
+
updatedRepo.put("repository_name", xAsset.getName());
XXPolicyExportAudit policyExportAudit = new XXPolicyExportAudit();
+
policyExportAudit.setRepositoryName(xAsset.getName());
if (agentId != null && !agentId.isEmpty()) {
@@ -194,22 +222,23 @@ public String getLatestRepoPolicy(VXAsset xAsset, List xResourceList
if (!httpEnabled) {
if (!isSecure) {
policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
+
createPolicyAudit(policyExportAudit);
- throw restErrorUtil.createRESTException("Unauthorized access -" + " only https allowed", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ throw restErrorUtil.createRESTException("Unauthorized access - only https allowed", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
}
if (certchain == null || certchain.length == 0) {
policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
+
createPolicyAudit(policyExportAudit);
- throw restErrorUtil.createRESTException("Unauthorized access -" + " unable to get client certificate", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
+ throw restErrorUtil.createRESTException("Unauthorized access - unable to get client certificate", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
}
}
- Long policyCount = restErrorUtil.parseLong(count, "Invalid value for " + "policyCount", MessageEnums.INVALID_INPUT_DATA, null, "policyCount");
-
- String commonName = null;
+ Long policyCount = restErrorUtil.parseLong(count, "Invalid value for policyCount", MessageEnums.INVALID_INPUT_DATA, null, "policyCount");
+ String commonName = null;
if (certchain != null) {
X509Certificate clientCert = certchain[0];
@@ -217,23 +246,28 @@ public String getLatestRepoPolicy(VXAsset xAsset, List xResourceList
try {
LdapName ln = new LdapName(dn);
+
for (Rdn rdn : ln.getRdns()) {
if ("CN".equalsIgnoreCase(rdn.getType())) {
commonName = rdn.getValue() + "";
break;
}
}
+
if (commonName == null) {
policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
+
createPolicyAudit(policyExportAudit);
throw restErrorUtil.createRESTException("Unauthorized access - Unable to find Common Name from [" + dn + "]", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
}
} catch (InvalidNameException e) {
policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
+
createPolicyAudit(policyExportAudit);
logger.error("Invalid Common Name.", e);
+
throw restErrorUtil.createRESTException("Unauthorized access - Invalid Common Name", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
}
}
@@ -249,6 +283,7 @@ public String getLatestRepoPolicy(VXAsset xAsset, List xResourceList
if (!commonName.equalsIgnoreCase(cnFromConfig)) {
policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
+
createPolicyAudit(policyExportAudit);
throw restErrorUtil.createRESTException("Unauthorized access. expected [" + cnFromConfig + "], found [" + commonName + "]", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
@@ -262,27 +297,30 @@ public String getLatestRepoPolicy(VXAsset xAsset, List xResourceList
if (policyCount == resourceListSz) {
policyExportAudit.setHttpRetCode(HttpServletResponse.SC_NOT_MODIFIED);
+
createPolicyAudit(policyExportAudit);
throw restErrorUtil.createRESTException(HttpServletResponse.SC_NOT_MODIFIED, "No change since last update", false);
}
}
- List> resourceList = new ArrayList>();
+ List> resourceList = new ArrayList<>();
// HDFS Repository
if (xAsset.getAssetType() == AppConstants.ASSET_HDFS) {
for (VXResource xResource : xResourceList) {
HashMap resourceMap = new HashMap<>();
+
resourceMap.put("id", xResource.getId());
resourceMap.put("resource", xResource.getName());
resourceMap.put("isRecursive", getBooleanValue(xResource.getIsRecursive()));
resourceMap.put("policyStatus", RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus()));
- // resourceMap.put("isEncrypt",
- // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt()));
+ // resourceMap.put("isEncrypt", AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt()));
populatePermMap(xResource, resourceMap, AppConstants.ASSET_HDFS);
+
List xAuditMaps = xResource.getAuditList();
- if (xAuditMaps.size() != 0) {
+
+ if (!xAuditMaps.isEmpty()) {
resourceMap.put("audit", 1);
} else {
resourceMap.put("audit", 0);
@@ -293,12 +331,15 @@ public String getLatestRepoPolicy(VXAsset xAsset, List xResourceList
} else if (xAsset.getAssetType() == AppConstants.ASSET_HIVE) {
for (VXResource xResource : xResourceList) {
HashMap resourceMap = new HashMap<>();
+
resourceMap.put("id", xResource.getId());
resourceMap.put("database_name", xResource.getDatabases());
resourceMap.put("policyStatus", RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus()));
resourceMap.put("tablePolicyType", AppConstants.getLabelFor_PolicyType(xResource.getTableType()));
resourceMap.put("columnPolicyType", AppConstants.getLabelFor_PolicyType(xResource.getColumnType()));
+
int resourceType = xResource.getResourceType();
+
if (resourceType == AppConstants.RESOURCE_UDF) {
resourceMap.put("udf_name", xResource.getUdfs());
} else if (resourceType == AppConstants.RESOURCE_COLUMN) {
@@ -311,11 +352,13 @@ public String getLatestRepoPolicy(VXAsset xAsset, List xResourceList
populatePermMap(xResource, resourceMap, AppConstants.ASSET_HIVE);
List xAuditMaps = xResource.getAuditList();
- if (xAuditMaps.size() != 0) {
+
+ if (!xAuditMaps.isEmpty()) {
resourceMap.put("audit", 1);
} else {
resourceMap.put("audit", 0);
}
+
resourceList.add(resourceMap);
}
} else if (xAsset.getAssetType() == AppConstants.ASSET_HBASE) {
@@ -327,20 +370,24 @@ public String getLatestRepoPolicy(VXAsset xAsset, List xResourceList
resourceMap.put("column_name", xResource.getColumns());
resourceMap.put("column_families", xResource.getColumnFamilies());
resourceMap.put("policyStatus", RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus()));
+
if (xResource.getIsEncrypt() == 1) {
resourceMap.put("encrypt", 1);
} else {
resourceMap.put("encrypt", 0);
}
- // resourceMap.put("isEncrypt",
- // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt()));
+
+ // resourceMap.put("isEncrypt", AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt()));
populatePermMap(xResource, resourceMap, AppConstants.ASSET_HBASE);
+
List xAuditMaps = xResource.getAuditList();
- if (xAuditMaps.size() != 0) {
+
+ if (!xAuditMaps.isEmpty()) {
resourceMap.put("audit", 1);
} else {
resourceMap.put("audit", 0);
}
+
resourceList.add(resourceMap);
}
} else if (xAsset.getAssetType() == AppConstants.ASSET_KNOX) {
@@ -351,20 +398,24 @@ public String getLatestRepoPolicy(VXAsset xAsset, List xResourceList
resourceMap.put("topology_name", xResource.getTopologies());
resourceMap.put("service_name", xResource.getServices());
resourceMap.put("policyStatus", RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus()));
+
if (xResource.getIsEncrypt() == 1) {
resourceMap.put("encrypt", 1);
} else {
resourceMap.put("encrypt", 0);
}
- // resourceMap.put("isEncrypt",
- // AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt()));
+
+ // resourceMap.put("isEncrypt", AKAConstants.getLabelFor_BooleanValue(xResource.getIsEncrypt()));
populatePermMap(xResource, resourceMap, AppConstants.ASSET_KNOX);
+
List xAuditMaps = xResource.getAuditList();
- if (xAuditMaps.size() != 0) {
+
+ if (!xAuditMaps.isEmpty()) {
resourceMap.put("audit", 1);
} else {
resourceMap.put("audit", 0);
}
+
resourceList.add(resourceMap);
}
} else if (xAsset.getAssetType() == AppConstants.ASSET_STORM) {
@@ -374,34 +425,54 @@ public String getLatestRepoPolicy(VXAsset xAsset, List xResourceList
resourceMap.put("id", xResource.getId());
resourceMap.put("topology_name", xResource.getTopologies());
resourceMap.put("policyStatus", RangerCommonEnums.getLabelFor_ActiveStatus(xResource.getResourceStatus()));
+
if (xResource.getIsEncrypt() == 1) {
resourceMap.put("encrypt", 1);
} else {
resourceMap.put("encrypt", 0);
}
+
populatePermMap(xResource, resourceMap, AppConstants.ASSET_STORM);
+
List xAuditMaps = xResource.getAuditList();
- if (xAuditMaps.size() != 0) {
+
+ if (!xAuditMaps.isEmpty()) {
resourceMap.put("audit", 1);
} else {
resourceMap.put("audit", 0);
}
+
resourceList.add(resourceMap);
}
} else {
policyExportAudit.setHttpRetCode(HttpServletResponse.SC_BAD_REQUEST);
+
createPolicyAudit(policyExportAudit);
+
throw restErrorUtil.createRESTException("The operation isn't yet supported for the repository", MessageEnums.OPER_NOT_ALLOWED_FOR_ENTITY);
}
- policyCount = Long.valueOf(resourceList.size());
+ policyCount = (long) resourceList.size();
+
updatedRepo.put("last_updated", updatedTime);
updatedRepo.put("policyCount", policyCount);
updatedRepo.put("acl", resourceList);
String updatedPolicyStr = jsonUtil.readMapToString(updatedRepo);
+ // File file = null;
+ // try {
+ // file = jsonUtil.writeMapToFile(updatedRepo, repository);
+ // } catch (JsonGenerationException e) {
+ // logger.error("Error exporting policies for repository : {}", repository, e);
+ // } catch (JsonMappingException e) {
+ // logger.error("Error exporting policies for repository : {}", repository, e);
+ // } catch (IOException e) {
+ // logger.error("Error exporting policies for repository : {}", repository, e);
+ // }
+
policyExportAudit.setHttpRetCode(HttpServletResponse.SC_OK);
+
createPolicyAudit(policyExportAudit);
return updatedPolicyStr;
@@ -411,31 +482,37 @@ public void updateDefaultPolicyUserAndPerm(VXResource vXResource, String userNam
if (userName != null && !userName.isEmpty()) {
XXUser xxUser = rangerDaoManager.getXXUser().findByUserName(userName);
VXUser vXUser;
+
if (xxUser != null) {
vXUser = xUserService.populateViewBean(xxUser);
} else {
vXUser = new VXUser();
+
vXUser.setName(userName);
// FIXME hack : unnecessary.
vXUser.setDescription(userName);
+
vXUser = xUserService.createResource(vXUser);
}
- // fetch old permission and consider only one permission for default
- // policy
+
+ // fetch old permission and consider only one permission for default policy
List xxPermMapList = rangerDaoManager.getXXPermMap().findByResourceId(vXResource.getId());
VXPermMap vXPermMap = null;
- if (xxPermMapList != null && xxPermMapList.size() != 0) {
+
+ if (xxPermMapList != null && !xxPermMapList.isEmpty()) {
vXPermMap = xPermMapService.populateViewBean(xxPermMapList.get(0));
}
if (vXPermMap == null) {
// create new permission
vXPermMap = new VXPermMap();
+
vXPermMap.setUserId(vXUser.getId());
vXPermMap.setResourceId(vXResource.getId());
} else {
// update old permission after updating userid
vXPermMap.setUserId(vXUser.getId());
+
xPermMapService.updateResource(vXPermMap);
}
}
@@ -443,6 +520,7 @@ public void updateDefaultPolicyUserAndPerm(VXResource vXResource, String userNam
public void createPolicyAudit(final XXPolicyExportAudit xXPolicyExportAudit) {
final Runnable commitWork;
+
if (xXPolicyExportAudit.getHttpRetCode() == HttpServletResponse.SC_NOT_MODIFIED) {
if (!rangerLogNotModified) {
logger.debug("Not logging HttpServletResponse. SC_NOT_MODIFIED. To enable, set configuration: {}=true", PROP_RANGER_LOG_SC_NOT_MODIFIED);
@@ -452,20 +530,10 @@ public void createPolicyAudit(final XXPolicyExportAudit xXPolicyExportAudit) {
// Create PolicyExportAudit record after transaction is completed. If it is created in-line here
// then the TransactionManager will roll-back the changes because the HTTP return code is
// HttpServletResponse.SC_NOT_MODIFIED
- commitWork = new Runnable() {
- @Override
- public void run() {
- rangerDaoManager.getXXPolicyExportAudit().create(xXPolicyExportAudit);
- }
- };
+ commitWork = () -> rangerDaoManager.getXXPolicyExportAudit().create(xXPolicyExportAudit);
}
} else {
- commitWork = new Runnable() {
- @Override
- public void run() {
- rangerDaoManager.getXXPolicyExportAudit().create(xXPolicyExportAudit);
- }
- };
+ commitWork = () -> rangerDaoManager.getXXPolicyExportAudit().create(xXPolicyExportAudit);
}
if (commitWork != null) {
@@ -478,15 +546,15 @@ public void run() {
}
public void createPluginInfo(String serviceName, String pluginId, HttpServletRequest request, int entityType, Long downloadedVersion, Long lastKnownVersion, long lastActivationTime, int httpCode, String clusterName, String pluginCapabilities) {
- RangerRESTUtils restUtils = new RangerRESTUtils();
-
- final String ipAddress = getRemoteAddress(request);
- final String appType = restUtils.getAppIdFromPluginId(pluginId);
+ RangerRESTUtils restUtils = new RangerRESTUtils();
+ final String ipAddress = getRemoteAddress(request);
+ final String appType = restUtils.getAppIdFromPluginId(pluginId);
+ String tmpHostName = null;
- String tmpHostName = null;
if (StringUtils.isNotBlank(pluginId)) {
tmpHostName = restUtils.getHostnameFromPluginId(pluginId, serviceName);
}
+
if (StringUtils.isBlank(tmpHostName) && request != null) {
tmpHostName = request.getRemoteHost();
}
@@ -545,22 +613,29 @@ public VXTrxLogList getReportLogs(SearchCriteria searchCriteria) {
if (searchCriteria.getParamList() != null && !searchCriteria.getParamList().isEmpty()) {
int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset();
- Date temp = null;
DateUtil dateUtil = new DateUtil();
+
if (searchCriteria.getParamList().containsKey("startDate")) {
- temp = (Date) searchCriteria.getParamList().get("startDate");
+ Date temp = (Date) searchCriteria.getParamList().get("startDate");
+
temp = dateUtil.getDateFromGivenDate(temp, 0, 0, 0, 0);
temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+
searchCriteria.getParamList().put("startDate", temp);
}
+
if (searchCriteria.getParamList().containsKey("endDate")) {
- temp = (Date) searchCriteria.getParamList().get("endDate");
+ Date temp = (Date) searchCriteria.getParamList().get("endDate");
+
temp = dateUtil.getDateFromGivenDate(temp, 0, 23, 59, 59);
temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+
searchCriteria.getParamList().put("endDate", temp);
}
+
if (searchCriteria.getParamList().containsKey("owner")) {
XXPortalUser xXPortalUser = rangerDaoManager.getXXPortalUser().findByLoginId((searchCriteria.getParamList().get("owner").toString()));
+
if (xXPortalUser != null) {
searchCriteria.getParamList().put("owner", xXPortalUser.getId());
} else {
@@ -592,23 +667,30 @@ public VXAccessAuditList getAccessLogs(SearchCriteria searchCriteria) {
if (searchCriteria == null) {
searchCriteria = new SearchCriteria();
}
+
if (searchCriteria.getParamList() != null && !searchCriteria.getParamList().isEmpty()) {
int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset();
- Date temp = null;
DateUtil dateUtil = new DateUtil();
+
if (searchCriteria.getParamList().containsKey("startDate")) {
- temp = (Date) searchCriteria.getParamList().get("startDate");
+ Date temp = (Date) searchCriteria.getParamList().get("startDate");
+
temp = dateUtil.getDateFromGivenDate(temp, 0, 0, 0, 0);
temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+
searchCriteria.getParamList().put("startDate", temp);
}
+
if (searchCriteria.getParamList().containsKey("endDate")) {
- temp = (Date) searchCriteria.getParamList().get("endDate");
+ Date temp = (Date) searchCriteria.getParamList().get("endDate");
+
temp = dateUtil.getDateFromGivenDate(temp, 0, 23, 59, 59);
temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+
searchCriteria.getParamList().put("endDate", temp);
}
}
+
if (searchCriteria.getSortType() == null) {
searchCriteria.setSortType("desc");
} else if (!"asc".equalsIgnoreCase(searchCriteria.getSortType()) && !"desc".equalsIgnoreCase(searchCriteria.getSortType())) {
@@ -618,25 +700,24 @@ public VXAccessAuditList getAccessLogs(SearchCriteria searchCriteria) {
if (!xaBizUtil.isAdmin()) {
Long userId = xaBizUtil.getXUserId();
List userZones = rangerDaoManager.getXXSecurityZoneDao().findZoneNamesByUserId(userId);
- Set zoneNameSet = new HashSet(userZones);
+ Set zoneNameSet = new HashSet<>(userZones);
+ VXGroupList groupList = xUserMgr.getXUserGroups(userId);
- VXGroupList groupList = xUserMgr.getXUserGroups(userId);
for (VXGroup group : groupList.getList()) {
List userGroupZones = rangerDaoManager.getXXSecurityZoneDao().findZoneNamesByGroupId(group.getId());
- for (String zoneName : userGroupZones) {
- zoneNameSet.add(zoneName);
- }
+
+ zoneNameSet.addAll(userGroupZones);
}
List zoneNameList = (List) searchCriteria.getParamValue("zoneName");
if ((zoneNameList == null || zoneNameList.isEmpty())) {
if (!zoneNameSet.isEmpty()) {
- searchCriteria.getParamList().put("zoneName", new ArrayList(zoneNameSet));
+ searchCriteria.getParamList().put("zoneName", new ArrayList<>(zoneNameSet));
} else {
searchCriteria.getParamList().put("zoneName", null);
}
- } else if (!zoneNameList.isEmpty() && !zoneNameSet.isEmpty()) {
+ } else if (!zoneNameSet.isEmpty()) {
for (String znName : zoneNameList) {
if (!serviceMgr.isZoneAdmin(znName) && !serviceMgr.isZoneAuditor(znName)) {
throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not the zone admin or zone auditor of zone " + znName, true);
@@ -694,17 +775,21 @@ public List validateXXTrxLogList(List xTrxLogList) {
if (vXTrxLog.getPreviousValue() == null || "null".equalsIgnoreCase(vXTrxLog.getPreviousValue())) {
vXTrxLog.setPreviousValue("");
}
+
if (vXTrxLog.getNewValue() == null || "null".equalsIgnoreCase(vXTrxLog.getNewValue())) {
vXTrxLog.setNewValue("");
}
+
if (vXTrxLog.getAttributeName() != null && "Password".equalsIgnoreCase(vXTrxLog.getAttributeName())) {
vXTrxLog.setPreviousValue("*********");
vXTrxLog.setNewValue("***********");
}
+
if (vXTrxLog.getAttributeName() != null && "Connection Configurations".equalsIgnoreCase(vXTrxLog.getAttributeName())) {
if (vXTrxLog.getPreviousValue() != null && vXTrxLog.getPreviousValue().contains("password")) {
String tempPreviousStr = vXTrxLog.getPreviousValue();
String[] tempPreviousArr = vXTrxLog.getPreviousValue().split(",");
+
for (String tempPrevious : tempPreviousArr) {
if (tempPrevious.contains("{\"password") && tempPrevious.contains("}")) {
vXTrxLog.setPreviousValue(tempPreviousStr.replace(tempPrevious, "{\"password\":\"*****\"}"));
@@ -721,9 +806,11 @@ public List validateXXTrxLogList(List xTrxLogList) {
}
}
}
+
if (vXTrxLog.getNewValue() != null && vXTrxLog.getNewValue().contains("password")) {
String tempNewStr = vXTrxLog.getNewValue();
String[] tempNewArr = vXTrxLog.getNewValue().split(",");
+
for (String tempNew : tempNewArr) {
if (tempNew.contains("{\"password") && tempNew.contains("}")) {
vXTrxLog.setNewValue(tempNewStr.replace(tempNew, "{\"password\":\"*****\"}"));
@@ -744,6 +831,7 @@ public List validateXXTrxLogList(List xTrxLogList) {
vXTrxLogs.add(vXTrxLog);
}
+
return vXTrxLogs;
}
@@ -762,21 +850,26 @@ public VXPolicyExportAuditList searchXPolicyExportAudits(SearchCriteria searchCr
if (searchCriteria.getParamList() != null && !searchCriteria.getParamList().isEmpty()) {
int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset();
- Date temp = null;
DateUtil dateUtil = new DateUtil();
+
if (searchCriteria.getParamList().containsKey("startDate")) {
- temp = (Date) searchCriteria.getParamList().get("startDate");
+ Date temp = (Date) searchCriteria.getParamList().get("startDate");
+
temp = dateUtil.getDateFromGivenDate(temp, 0, 0, 0, 0);
temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+
searchCriteria.getParamList().put("startDate", temp);
}
if (searchCriteria.getParamList().containsKey("endDate")) {
- temp = (Date) searchCriteria.getParamList().get("endDate");
+ Date temp = (Date) searchCriteria.getParamList().get("endDate");
+
temp = dateUtil.getDateFromGivenDate(temp, 0, 23, 59, 59);
temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+
searchCriteria.getParamList().put("endDate", temp);
}
}
+
return xPolicyExportAuditService.searchXPolicyExportAudits(searchCriteria);
}
@@ -784,31 +877,38 @@ public VXUgsyncAuditInfoList getUgsyncAudits(SearchCriteria searchCriteria) {
if (!msBizUtil.hasModuleAccess(RangerConstants.MODULE_AUDIT)) {
throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not having permissions on the " + RangerConstants.MODULE_AUDIT + " module.", true);
}
+
if (searchCriteria == null) {
searchCriteria = new SearchCriteria();
}
+
if (searchCriteria.getParamList() != null && !searchCriteria.getParamList().isEmpty()) {
int clientTimeOffsetInMinute = RestUtil.getClientTimeOffset();
- Date temp = null;
DateUtil dateUtil = new DateUtil();
if (searchCriteria.getParamList().containsKey("startDate")) {
- temp = (Date) searchCriteria.getParamList().get("startDate");
+ Date temp = (Date) searchCriteria.getParamList().get("startDate");
+
temp = dateUtil.getDateFromGivenDate(temp, 0, 0, 0, 0);
temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+
searchCriteria.getParamList().put("startDate", temp);
}
if (searchCriteria.getParamList().containsKey("endDate")) {
- temp = (Date) searchCriteria.getParamList().get("endDate");
+ Date temp = (Date) searchCriteria.getParamList().get("endDate");
+
temp = dateUtil.getDateFromGivenDate(temp, 0, 23, 59, 59);
temp = dateUtil.addTimeOffset(temp, clientTimeOffsetInMinute);
+
searchCriteria.getParamList().put("endDate", temp);
}
}
+
if (searchCriteria.getSortType() == null) {
searchCriteria.setSortType("desc");
} else if (!"asc".equalsIgnoreCase(searchCriteria.getSortType()) && !"desc".equalsIgnoreCase(searchCriteria.getSortType())) {
searchCriteria.setSortType("desc");
}
+
return xUgsyncAuditInfoService.searchXUgsyncAuditInfoList(searchCriteria);
}
@@ -816,6 +916,7 @@ public VXUgsyncAuditInfoList getUgsyncAuditsBySyncSource(String syncSource) {
if (!msBizUtil.hasModuleAccess(RangerConstants.MODULE_AUDIT)) {
throw restErrorUtil.createRESTException(HttpServletResponse.SC_FORBIDDEN, "User is not having permissions on the " + RangerConstants.MODULE_AUDIT + " module.", true);
}
+
if (syncSource != null && !syncSource.trim().isEmpty()) {
return xUgsyncAuditInfoService.searchXUgsyncAuditInfoBySyncSource(syncSource);
} else {
@@ -826,19 +927,21 @@ public VXUgsyncAuditInfoList getUgsyncAuditsBySyncSource(String syncSource) {
@SuppressWarnings("unchecked")
private HashMap populatePermMap(VXResource xResource, HashMap resourceMap, int assetType) {
List xPermMapList = xResource.getPermMapList();
+ Set groupList = new HashSet<>();
- Set groupList = new HashSet<>();
for (VXPermMap xPermMap : xPermMapList) {
groupList.add(xPermMap.getId());
}
- List> sortedPermMapGroupList = new ArrayList>();
+ List> sortedPermMapGroupList = new ArrayList<>();
// Loop for adding group perms
for (VXPermMap xPermMap : xPermMapList) {
String groupKey = xPermMap.getPermGroup();
+
if (groupKey != null) {
boolean found = false;
+
for (HashMap sortedPermMap : sortedPermMapGroupList) {
if (sortedPermMap.containsValue(groupKey)) {
found = true;
@@ -851,6 +954,7 @@ private HashMap populatePermMap(VXResource xResource, HashMap populatePermMap(VXResource xResource, HashMap access = (Set) sortedPermMap.get("access");
String perm = AppConstants.getLabelFor_XAPermType(xPermMap.getPermType());
+
access.add(perm);
+
sortedPermMap.put("access", access);
}
}
if (!found) {
HashMap sortedPermMap = new HashMap<>();
+
sortedPermMap.put("groupKey", xPermMap.getPermGroup());
Set permSet = new HashSet<>();
String perm = AppConstants.getLabelFor_XAPermType(xPermMap.getPermType());
+
permSet.add(perm);
sortedPermMap.put("access", permSet);
if (assetType == AppConstants.ASSET_KNOX) {
String[] ipAddrList = new String[0];
+
if (xPermMap.getIpAddress() != null) {
ipAddrList = xPermMap.getIpAddress().split(",");
+
sortedPermMap.put("ipAddress", ipAddrList);
} else {
sortedPermMap.put("ipAddress", ipAddrList);
@@ -894,12 +1005,16 @@ private HashMap populatePermMap(VXResource xResource, HashMap groupSet = new HashSet<>();
String group = xPermMap.getGroupName();
+
groupSet.add(group);
+
sortedPermMap.put("groups", groupSet);
} else if (userId != null) {
Set userSet = new HashSet<>();
String user = xPermMap.getUserName();
+
userSet.add(user);
+
sortedPermMap.put("users", userSet);
}
@@ -917,6 +1032,7 @@ private HashMap populatePermMap(VXResource xResource, HashMap doCreateOrUpdateXXPluginInfo(pluginInfo, entityType, isTagVersionResetNeeded, clusterName);
}
} else if (httpCode == HttpServletResponse.SC_NOT_FOUND) {
- if ((isPolicyDownloadRequest(entityType) && (pluginInfo.getPolicyActiveVersion() == null || pluginInfo.getPolicyActiveVersion() == -1)) || (isTagDownloadRequest(entityType) && (pluginInfo.getTagActiveVersion() == null || pluginInfo.getTagActiveVersion() == -1)) || (isRoleDownloadRequest(entityType) && (pluginInfo.getRoleActiveVersion() == null || pluginInfo.getRoleActiveVersion() == -1)) || (isUserStoreDownloadRequest(entityType) && (pluginInfo.getUserStoreActiveVersion() == null || pluginInfo.getUserStoreActiveVersion() == -1)) || (isGdsDownloadRequest(entityType) && (pluginInfo.getGdsActiveVersion() == null || pluginInfo.getGdsActiveVersion() == -1))) {
- commitWork = new Runnable() {
- @Override
- public void run() {
- doDeleteXXPluginInfo(pluginInfo);
- }
- };
+ if ((isPolicyDownloadRequest(entityType) && (pluginInfo.getPolicyActiveVersion() == null || pluginInfo.getPolicyActiveVersion() == -1))
+ || (isTagDownloadRequest(entityType) && (pluginInfo.getTagActiveVersion() == null || pluginInfo.getTagActiveVersion() == -1))
+ || (isRoleDownloadRequest(entityType) && (pluginInfo.getRoleActiveVersion() == null || pluginInfo.getRoleActiveVersion() == -1))
+ || (isUserStoreDownloadRequest(entityType) && (pluginInfo.getUserStoreActiveVersion() == null || pluginInfo.getUserStoreActiveVersion() == -1))
+ || (isGdsDownloadRequest(entityType) && (pluginInfo.getGdsActiveVersion() == null || pluginInfo.getGdsActiveVersion() == -1))) {
+ commitWork = () -> doDeleteXXPluginInfo(pluginInfo);
} else {
- commitWork = new Runnable() {
- @Override
- public void run() {
- doCreateOrUpdateXXPluginInfo(pluginInfo, entityType, false, clusterName);
- }
- };
+ commitWork = () -> doCreateOrUpdateXXPluginInfo(pluginInfo, entityType, false, clusterName);
}
} else {
isTagVersionResetNeeded = false;
- commitWork = new Runnable() {
- @Override
- public void run() {
- doCreateOrUpdateXXPluginInfo(pluginInfo, entityType, isTagVersionResetNeeded, clusterName);
- }
- };
+ commitWork = () -> doCreateOrUpdateXXPluginInfo(pluginInfo, entityType, isTagVersionResetNeeded, clusterName);
}
if (commitWork != null) {
@@ -1002,18 +1103,20 @@ public void run() {
}
private XXPluginInfo doCreateOrUpdateXXPluginInfo(RangerPluginInfo pluginInfo, int entityType, final boolean isTagVersionResetNeeded, String clusterName) {
- XXPluginInfo ret = null;
- Map infoMap = null;
+ XXPluginInfo ret = null;
if (StringUtils.isNotBlank(pluginInfo.getServiceName())) {
XXPluginInfo xObj = rangerDaoManager.getXXPluginInfo().find(pluginInfo.getServiceName(), pluginInfo.getHostName(), pluginInfo.getAppType());
if (xObj == null) {
- infoMap = pluginInfo.getInfo();
+ Map infoMap = pluginInfo.getInfo();
+
if (!stringUtil.isEmpty(clusterName) && infoMap != null) {
infoMap.put(SearchFilter.CLUSTER_NAME, clusterName);
+
pluginInfo.setInfo(infoMap);
}
+
// ranger-admin is restarted, plugin contains latest versions and no earlier record for this plug-in client
if (isPolicyDownloadRequest(entityType)) {
if (pluginInfo.getPolicyDownloadedVersion() != null && pluginInfo.getPolicyDownloadedVersion().equals(pluginInfo.getPolicyActiveVersion())) {
@@ -1047,29 +1150,35 @@ private XXPluginInfo doCreateOrUpdateXXPluginInfo(RangerPluginInfo pluginInfo, i
xObj = pluginInfoService.populateDBObject(pluginInfo);
logger.debug("Creating RangerPluginInfo record for service-version");
+
ret = rangerDaoManager.getXXPluginInfo().create(xObj);
} else {
- boolean needsUpdating = false;
-
- RangerPluginInfo dbObj = pluginInfoService.populateViewObject(xObj);
+ boolean needsUpdating = false;
+ RangerPluginInfo dbObj = pluginInfoService.populateViewObject(xObj);
+ Map infoMap = dbObj.getInfo();
- infoMap = dbObj.getInfo();
if (infoMap != null && !stringUtil.isEmpty(clusterName)) {
if (!stringUtil.isEmpty(infoMap.get(SearchFilter.CLUSTER_NAME)) && !stringUtil.equals(infoMap.get(SearchFilter.CLUSTER_NAME), clusterName)) {
infoMap.put(SearchFilter.CLUSTER_NAME, clusterName);
+
needsUpdating = true;
}
}
+
if (!dbObj.getIpAddress().equals(pluginInfo.getIpAddress())) {
dbObj.setIpAddress(pluginInfo.getIpAddress());
+
needsUpdating = true;
}
+
if (isPolicyDownloadRequest(entityType)) {
if (dbObj.getPolicyDownloadedVersion() == null || !dbObj.getPolicyDownloadedVersion().equals(pluginInfo.getPolicyDownloadedVersion())) {
dbObj.setPolicyDownloadedVersion(pluginInfo.getPolicyDownloadedVersion());
dbObj.setPolicyDownloadTime(pluginInfo.getPolicyDownloadTime());
+
needsUpdating = true;
}
+
Long lastKnownPolicyVersion = pluginInfo.getPolicyActiveVersion();
Long lastPolicyActivationTime = pluginInfo.getPolicyActivationTime();
String lastPluginCapabilityVector = pluginInfo.getPluginCapabilities();
@@ -1077,22 +1186,31 @@ private XXPluginInfo doCreateOrUpdateXXPluginInfo(RangerPluginInfo pluginInfo, i
if (lastKnownPolicyVersion != null && lastKnownPolicyVersion == -1) {
// First download request after plug-in's policy-refresher starts
dbObj.setPolicyDownloadTime(pluginInfo.getPolicyDownloadTime());
+
needsUpdating = true;
}
+
if (lastKnownPolicyVersion != null && lastKnownPolicyVersion > 0 && (dbObj.getPolicyActiveVersion() == null || !dbObj.getPolicyActiveVersion().equals(lastKnownPolicyVersion))) {
dbObj.setPolicyActiveVersion(lastKnownPolicyVersion);
+
needsUpdating = true;
}
+
if (lastPolicyActivationTime != null && lastPolicyActivationTime > 0 && (dbObj.getPolicyActivationTime() == null || !dbObj.getPolicyActivationTime().equals(lastPolicyActivationTime))) {
dbObj.setPolicyActivationTime(lastPolicyActivationTime);
+
needsUpdating = true;
}
+
if (lastPluginCapabilityVector != null && (dbObj.getPluginCapabilities() == null || !dbObj.getPluginCapabilities().equals(lastPluginCapabilityVector))) {
dbObj.setPluginCapabilities(lastPluginCapabilityVector);
+
needsUpdating = true;
}
+
if (dbObj.getAdminCapabilities() == null || !dbObj.getAdminCapabilities().equals(adminCapabilities)) {
dbObj.setAdminCapabilities(adminCapabilities);
+
needsUpdating = true;
}
} else if (isTagDownloadRequest(entityType)) {
@@ -1100,6 +1218,7 @@ private XXPluginInfo doCreateOrUpdateXXPluginInfo(RangerPluginInfo pluginInfo, i
// First download for tags after tag-service is associated with resource-service
dbObj.setTagDownloadedVersion(pluginInfo.getTagDownloadedVersion());
dbObj.setTagDownloadTime(pluginInfo.getTagDownloadTime());
+
needsUpdating = true;
}
@@ -1109,21 +1228,26 @@ private XXPluginInfo doCreateOrUpdateXXPluginInfo(RangerPluginInfo pluginInfo, i
if (lastKnownTagVersion != null && lastKnownTagVersion == -1) {
// First download request after plug-in's tag-refresher restarts
dbObj.setTagDownloadTime(pluginInfo.getTagDownloadTime());
+
needsUpdating = true;
}
+
if (lastKnownTagVersion != null && lastKnownTagVersion > 0 && (dbObj.getTagActiveVersion() == null || !dbObj.getTagActiveVersion().equals(lastKnownTagVersion))) {
dbObj.setTagActiveVersion(lastKnownTagVersion);
+
needsUpdating = true;
}
if (lastTagActivationTime != null && lastTagActivationTime > 0 && (dbObj.getTagActivationTime() == null || !dbObj.getTagActivationTime().equals(lastTagActivationTime))) {
dbObj.setTagActivationTime(lastTagActivationTime);
+
needsUpdating = true;
}
} else if (isRoleDownloadRequest(entityType)) {
if (dbObj.getRoleDownloadedVersion() == null || !dbObj.getRoleDownloadedVersion().equals(pluginInfo.getRoleDownloadedVersion())) {
dbObj.setRoleDownloadedVersion(pluginInfo.getRoleDownloadedVersion());
dbObj.setRoleDownloadTime(pluginInfo.getRoleDownloadTime());
+
needsUpdating = true;
}
@@ -1132,22 +1256,26 @@ private XXPluginInfo doCreateOrUpdateXXPluginInfo(RangerPluginInfo pluginInfo, i
if (lastKnownRoleVersion != null && lastKnownRoleVersion == -1) {
dbObj.setRoleDownloadTime(pluginInfo.getRoleDownloadTime());
+
needsUpdating = true;
}
if (lastKnownRoleVersion != null && lastKnownRoleVersion > 0 && (dbObj.getRoleActiveVersion() == null || !dbObj.getRoleActiveVersion().equals(lastKnownRoleVersion))) {
dbObj.setRoleActiveVersion(lastKnownRoleVersion);
+
needsUpdating = true;
}
if (lastRoleActivationTime != null && lastRoleActivationTime > 0 && (dbObj.getRoleActivationTime() == null || !dbObj.getRoleActivationTime().equals(lastRoleActivationTime))) {
dbObj.setRoleActivationTime(lastRoleActivationTime);
+
needsUpdating = true;
}
} else if (isUserStoreDownloadRequest(entityType)) {
if (dbObj.getUserStoreDownloadedVersion() == null || !dbObj.getUserStoreDownloadedVersion().equals(pluginInfo.getUserStoreDownloadedVersion())) {
dbObj.setUserStoreDownloadedVersion(pluginInfo.getUserStoreDownloadedVersion());
dbObj.setUserStoreDownloadTime(pluginInfo.getUserStoreDownloadTime());
+
needsUpdating = true;
}
@@ -1156,22 +1284,26 @@ private XXPluginInfo doCreateOrUpdateXXPluginInfo(RangerPluginInfo pluginInfo, i
if (lastKnownUserStoreVersion != null && lastKnownUserStoreVersion == -1) {
dbObj.setUserStoreDownloadTime(pluginInfo.getUserStoreDownloadTime());
+
needsUpdating = true;
}
if (lastKnownUserStoreVersion != null && lastKnownUserStoreVersion > 0 && (dbObj.getUserStoreActiveVersion() == null || !dbObj.getUserStoreActiveVersion().equals(lastKnownUserStoreVersion))) {
dbObj.setUserStoreActiveVersion(lastKnownUserStoreVersion);
+
needsUpdating = true;
}
if (lastUserStoreActivationTime != null && lastUserStoreActivationTime > 0 && (dbObj.getUserStoreActivationTime() == null || !dbObj.getUserStoreActivationTime().equals(lastUserStoreActivationTime))) {
dbObj.setUserStoreActivationTime(lastUserStoreActivationTime);
+
needsUpdating = true;
}
} else if (isGdsDownloadRequest(entityType)) {
if (dbObj.getGdsDownloadedVersion() == null || !dbObj.getGdsDownloadedVersion().equals(pluginInfo.getGdsDownloadedVersion())) {
dbObj.setGdsDownloadedVersion(pluginInfo.getGdsDownloadedVersion());
dbObj.setGdsDownloadTime(pluginInfo.getGdsDownloadTime());
+
needsUpdating = true;
}
@@ -1180,16 +1312,19 @@ private XXPluginInfo doCreateOrUpdateXXPluginInfo(RangerPluginInfo pluginInfo, i
if (lastKnownGdsVersion != null && lastKnownGdsVersion == -1) {
dbObj.setGdsDownloadTime(pluginInfo.getGdsDownloadTime());
+
needsUpdating = true;
}
if (lastKnownGdsVersion != null && lastKnownGdsVersion > 0 && (dbObj.getGdsActiveVersion() == null || !dbObj.getGdsActiveVersion().equals(lastKnownGdsVersion))) {
dbObj.setGdsActiveVersion(lastKnownGdsVersion);
+
needsUpdating = true;
}
if (lastGdsActivationTime != null && lastGdsActivationTime > 0 && (dbObj.getGdsActivationTime() == null || !dbObj.getGdsActivationTime().equals(lastGdsActivationTime))) {
dbObj.setGdsActivationTime(lastGdsActivationTime);
+
needsUpdating = true;
}
}
@@ -1199,11 +1334,13 @@ private XXPluginInfo doCreateOrUpdateXXPluginInfo(RangerPluginInfo pluginInfo, i
dbObj.setTagDownloadTime(null);
dbObj.setTagActiveVersion(null);
dbObj.setTagActivationTime(null);
+
needsUpdating = true;
}
if (needsUpdating) {
logger.debug("Updating XXPluginInfo record for service-version");
+
xObj = pluginInfoService.populateDBObject(dbObj);
ret = rangerDaoManager.getXXPluginInfo().update(xObj);
@@ -1218,6 +1355,7 @@ private XXPluginInfo doCreateOrUpdateXXPluginInfo(RangerPluginInfo pluginInfo, i
private void doDeleteXXPluginInfo(RangerPluginInfo pluginInfo) {
XXPluginInfo xObj = rangerDaoManager.getXXPluginInfo().find(pluginInfo.getServiceName(), pluginInfo.getHostName(), pluginInfo.getAppType());
+
if (xObj != null) {
rangerDaoManager.getXXPluginInfo().remove(xObj.getId());
}
@@ -1228,17 +1366,21 @@ private String getRemoteAddress(final HttpServletRequest request) {
if (request != null) {
String xForwardedAddress = request.getHeader("X-Forwarded-For");
+
if (StringUtils.isNotBlank(xForwardedAddress)) {
String[] forwardedAddresses = xForwardedAddress.split(",");
+
if (forwardedAddresses.length > 0) {
// Use first one. Hope it is the IP of the originating client
ret = forwardedAddresses[0].trim();
}
}
+
if (ret == null) {
ret = request.getRemoteAddr();
}
}
+
return ret;
}
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/AssetMgrBase.java b/security-admin/src/main/java/org/apache/ranger/biz/AssetMgrBase.java
index 970cd745d6..50f6676908 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/AssetMgrBase.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/AssetMgrBase.java
@@ -51,11 +51,13 @@ public VXCredentialStore getXCredentialStore(Long id) {
public VXCredentialStore createXCredentialStore(VXCredentialStore vXCredentialStore) {
vXCredentialStore = xCredentialStoreService.createResource(vXCredentialStore);
+
return vXCredentialStore;
}
public VXCredentialStore updateXCredentialStore(VXCredentialStore vXCredentialStore) {
vXCredentialStore = xCredentialStoreService.updateResource(vXCredentialStore);
+
return vXCredentialStore;
}
@@ -81,11 +83,13 @@ public VXPolicyExportAudit getXPolicyExportAudit(Long id) {
public VXPolicyExportAudit createXPolicyExportAudit(VXPolicyExportAudit vXPolicyExportAudit) {
vXPolicyExportAudit = xPolicyExportAuditService.createResource(vXPolicyExportAudit);
+
return vXPolicyExportAudit;
}
public VXPolicyExportAudit updateXPolicyExportAudit(VXPolicyExportAudit vXPolicyExportAudit) {
vXPolicyExportAudit = xPolicyExportAuditService.updateResource(vXPolicyExportAudit);
+
return vXPolicyExportAudit;
}
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/BaseMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/BaseMgr.java
index 0803afb752..369958c68d 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/BaseMgr.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/BaseMgr.java
@@ -17,6 +17,9 @@
* under the License.
*/
+/**
+ *
+ */
package org.apache.ranger.biz;
import org.apache.ranger.common.MessageEnums;
@@ -46,12 +49,14 @@ public RangerDaoManager getDaoManager() {
public void deleteEntity(BaseDao extends XXDBBase> baseDao, Long id, String entityName) {
XXDBBase entity = baseDao.getById(id);
+
if (entity != null) {
try {
baseDao.remove(id);
} catch (Exception e) {
- logger.error("Error deleting {}. Id = {}", entityName, id, e);
- throw restErrorUtil.createRESTException("This " + entityName + " can't be deleted", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE, id, null, "" + id + ", error=" + e.getMessage());
+ logger.error("Error deleting {}. Id={}", entityName, id, e);
+
+ throw restErrorUtil.createRESTException("This " + entityName + " can't be deleted", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE, id, null, id + ", error=" + e.getMessage());
}
} else {
// Return without error
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/GdsDBStore.java b/security-admin/src/main/java/org/apache/ranger/biz/GdsDBStore.java
index 0656574970..7916f08188 100755
--- a/security-admin/src/main/java/org/apache/ranger/biz/GdsDBStore.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/GdsDBStore.java
@@ -22,7 +22,7 @@
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpStatus;
-import org.apache.ranger.biz.ServiceDBStore.RemoveRefType;
+import org.apache.ranger.biz.ServiceDBStore.REMOVE_REF_TYPE;
import org.apache.ranger.common.GUIDUtil;
import org.apache.ranger.common.MessageEnums;
import org.apache.ranger.common.RESTErrorUtil;
@@ -110,15 +110,17 @@
@Component
public class GdsDBStore extends AbstractGdsStore {
- public static final String RESOURCE_NAME_DATASET_ID = "dataset-id";
- public static final String RESOURCE_NAME_PROJECT_ID = "project-id";
- public static final String NOT_AUTHORIZED_FOR_DATASET_POLICIES = "User is not authorized to manage policies for this dataset";
- public static final String NOT_AUTHORIZED_TO_VIEW_DATASET_POLICIES = "User is not authorized to view policies for this dataset";
- public static final String NOT_AUTHORIZED_FOR_PROJECT_POLICIES = "User is not authorized to manage policies for this dataset";
- public static final String NOT_AUTHORIZED_TO_VIEW_PROJECT_POLICIES = "User is not authorized to view policies for this dataset";
- public static final String GDS_POLICY_NAME_TIMESTAMP_SEP = "@";
private static final Logger LOG = LoggerFactory.getLogger(GdsDBStore.class);
- private static final Set SHARE_STATUS_AGR = new HashSet<>(Arrays.asList(GdsShareStatus.ACTIVE.ordinal(), GdsShareStatus.GRANTED.ordinal(), GdsShareStatus.REQUESTED.ordinal()));
+
+ public static final String RESOURCE_NAME_DATASET_ID = "dataset-id";
+ public static final String RESOURCE_NAME_PROJECT_ID = "project-id";
+ public static final String NOT_AUTHORIZED_FOR_DATASET_POLICIES = "User is not authorized to manage policies for this dataset";
+ public static final String NOT_AUTHORIZED_TO_VIEW_DATASET_POLICIES = "User is not authorized to view policies for this dataset";
+ public static final String NOT_AUTHORIZED_FOR_PROJECT_POLICIES = "User is not authorized to manage policies for this dataset";
+ public static final String NOT_AUTHORIZED_TO_VIEW_PROJECT_POLICIES = "User is not authorized to view policies for this dataset";
+ public static final String GDS_POLICY_NAME_TIMESTAMP_SEP = "@";
+
+ private static final Set SHARE_STATUS_AGR = new HashSet<>(Arrays.asList(GdsShareStatus.ACTIVE.ordinal(), GdsShareStatus.GRANTED.ordinal(), GdsShareStatus.REQUESTED.ordinal()));
@Autowired
RangerGdsValidator validator;
@@ -171,6 +173,7 @@ public class GdsDBStore extends AbstractGdsStore {
@PostConstruct
public void initStore() {
LOG.debug("==> GdsInMemoryStore.initStore()");
+
LOG.debug("<== GdsInMemoryStore.initStore()");
}
@@ -773,10 +776,13 @@ public PList searchSharedResources(SearchFilter filter) {
final Collection resources = sharedResource.getResource().values();
if (CollectionUtils.isNotEmpty(resources)) {
- includeResource = resources.stream().filter(Objects::nonNull).map(RangerPolicyResource::getValues).filter(Objects::nonNull).anyMatch(res -> hasResource(res, resourceContains));
+ includeResource = resources.stream().filter(Objects::nonNull)
+ .map(RangerPolicyResource::getValues).filter(Objects::nonNull)
+ .anyMatch(res -> hasResource(res, resourceContains));
if (!includeResource && sharedResource.getSubResource() != null && CollectionUtils.isNotEmpty(sharedResource.getSubResource().getValues())) {
- includeResource = sharedResource.getSubResource().getValues().stream().filter(Objects::nonNull).anyMatch(value -> value.contains(resourceContains));
+ includeResource = sharedResource.getSubResource().getValues().stream().filter(Objects::nonNull)
+ .anyMatch(value -> value.contains(resourceContains));
}
}
}
@@ -1098,7 +1104,7 @@ public RangerPolicy getDatasetPolicy(Long datasetId, Long policyId) throws Excep
}
@Override
- public List getDatasetPolicies(Long datasetId) throws Exception {
+ public List getDatasetPolicies(Long datasetId) {
LOG.debug("==> getDatasetPolicies({})", datasetId);
RangerDataset dataset = datasetService.read(datasetId);
@@ -1227,7 +1233,7 @@ public RangerPolicy getProjectPolicy(Long projectId, Long policyId) throws Excep
}
@Override
- public List getProjectPolicies(Long projectId) throws Exception {
+ public List getProjectPolicies(Long projectId) {
LOG.debug("==> getProjectPolicies({})", projectId);
RangerProject project = projectService.read(projectId);
@@ -1351,7 +1357,7 @@ public List addDataSharesInDataset(List GdsDBStore.getGdsInfoIfUpdated({}, {})", serviceName, lastKnownVersion);
ServiceGdsInfo latest = serviceGdsInfoCache.get(serviceName);
@@ -1363,7 +1369,7 @@ public ServiceGdsInfo getGdsInfoIfUpdated(String serviceName, Long lastKnownVers
return ret;
}
- public PList getDatasetSummary(SearchFilter filter) throws Exception {
+ public PList getDatasetSummary(SearchFilter filter) {
LOG.debug("==> getDatasetSummary({})", filter);
PList datasets = getUnscrubbedDatasets(filter);
@@ -1505,7 +1511,7 @@ private void setUserId(SearchFilter filter, String filterParam) {
filter.setParam(filterParam, Long.toString(userId));
}
- private List toDatasetSummary(List datasets, GdsPermission gdsPermission) throws Exception {
+ private List toDatasetSummary(List datasets, GdsPermission gdsPermission) {
List ret = new ArrayList<>();
String currentUser = bizUtil.getCurrentUserLoginId();
@@ -1544,7 +1550,10 @@ private List toDatasetSummary(List datasets, GdsP
List dataSharesSummary = getDataSharesSummary(dataShares, filter);
datasetSummary.setDataShares(dataSharesSummary);
- datasetSummary.setTotalResourceCount(dataSharesSummary.stream().map(DataShareInDatasetSummary::getResourceCount).mapToLong(Long::longValue).sum());
+ datasetSummary.setTotalResourceCount(dataSharesSummary.stream()
+ .map(DataShareInDatasetSummary::getResourceCount)
+ .mapToLong(Long::longValue)
+ .sum());
}
return ret;
@@ -1602,7 +1611,7 @@ private Long getDIPCountForDataset(Long datasetId) {
return datasetInProjectService.getDatasetsInProjectCount(datasetId);
}
- private Map getPrincipalCountForDataset(RangerDataset dataset) throws Exception {
+ private Map getPrincipalCountForDataset(RangerDataset dataset) {
Map ret = new HashMap<>();
Set users = Collections.emptySet();
Set groups = Collections.emptySet();
@@ -1935,7 +1944,9 @@ private void removeDIPForDataset(Long datasetId) {
boolean dipDeleted = dipDao.remove(dip.getId());
if (!dipDeleted) {
- throw restErrorUtil.createRESTException("DatasetInProject could not be deleted", MessageEnums.ERROR_DELETE_OBJECT, dip.getId(), "DatasetInProjectId", null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ throw restErrorUtil.createRESTException("DatasetInProject could not be deleted",
+ MessageEnums.ERROR_DELETE_OBJECT, dip.getId(), "DatasetInProjectId", null,
+ HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
}
}
@@ -1948,7 +1959,9 @@ private void removeDSHIDForDataset(Long datasetId) {
boolean dshidDeleted = dshidDao.remove(dshid.getId());
if (!dshidDeleted) {
- throw restErrorUtil.createRESTException("DataShareInDataset could not be deleted", MessageEnums.ERROR_DELETE_OBJECT, dshid.getId(), "DataShareInDataset", null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ throw restErrorUtil.createRESTException("DataShareInDataset could not be deleted",
+ MessageEnums.ERROR_DELETE_OBJECT, dshid.getId(), "DataShareInDataset", null,
+ HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
}
}
@@ -1961,7 +1974,9 @@ private void removeDIPForProject(Long projectId) {
boolean dipDeleted = dipDao.remove(dip.getId());
if (!dipDeleted) {
- throw restErrorUtil.createRESTException("DatasetInProject could not be deleted", MessageEnums.ERROR_DELETE_OBJECT, dip.getId(), "DatasetInProjectId", null, HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ throw restErrorUtil.createRESTException("DatasetInProject could not be deleted",
+ MessageEnums.ERROR_DELETE_OBJECT, dip.getId(), "DatasetInProjectId", null,
+ HttpStatus.SC_INTERNAL_SERVER_ERROR);
}
}
}
@@ -2070,7 +2085,8 @@ private DataShareInDatasetSummary toDshInDsSummary(RangerDataset dataset, List zoneIds = new HashMap<>();
DataShareInDatasetSummary summary = new DataShareInDatasetSummary();
@@ -2210,7 +2226,7 @@ private List getPolicies(List policyIds) {
private void updateGdsVersionForService(Long serviceId) {
updateGdsVersion();
- Runnable serviceVersionUpdater = new ServiceDBStore.ServiceVersionUpdater(daoMgr, serviceId, ServiceDBStore.VersionType.GDS_VERSION, RangerPolicyDelta.CHANGE_TYPE_GDS_UPDATE);
+ Runnable serviceVersionUpdater = new ServiceDBStore.ServiceVersionUpdater(daoMgr, serviceId, ServiceDBStore.VERSION_TYPE.GDS_VERSION, RangerPolicyDelta.CHANGE_TYPE_GDS_UPDATE);
daoMgr.getRangerTransactionSynchronizationAdapter().executeOnTransactionCommit(serviceVersionUpdater);
}
@@ -2229,7 +2245,7 @@ private void updateGdsVersionForProject(Long projectId) {
List serviceIds = daoMgr.getXXGdsProject().findServiceIdsForProject(projectId);
for (Long serviceId : serviceIds) {
- Runnable serviceVersionUpdater = new ServiceDBStore.ServiceVersionUpdater(daoMgr, serviceId, ServiceDBStore.VersionType.GDS_VERSION, RangerPolicyDelta.CHANGE_TYPE_GDS_UPDATE);
+ Runnable serviceVersionUpdater = new ServiceDBStore.ServiceVersionUpdater(daoMgr, serviceId, ServiceDBStore.VERSION_TYPE.GDS_VERSION, RangerPolicyDelta.CHANGE_TYPE_GDS_UPDATE);
daoMgr.getRangerTransactionSynchronizationAdapter().executeOnTransactionCommit(serviceVersionUpdater);
}
@@ -2241,7 +2257,7 @@ private void updateGdsVersionForDataset(Long datasetId) {
List serviceIds = daoMgr.getXXGdsDataset().findServiceIdsForDataset(datasetId);
for (Long serviceId : serviceIds) {
- Runnable serviceVersionUpdater = new ServiceDBStore.ServiceVersionUpdater(daoMgr, serviceId, ServiceDBStore.VersionType.GDS_VERSION, RangerPolicyDelta.CHANGE_TYPE_GDS_UPDATE);
+ Runnable serviceVersionUpdater = new ServiceDBStore.ServiceVersionUpdater(daoMgr, serviceId, ServiceDBStore.VERSION_TYPE.GDS_VERSION, RangerPolicyDelta.CHANGE_TYPE_GDS_UPDATE);
daoMgr.getRangerTransactionSynchronizationAdapter().executeOnTransactionCommit(serviceVersionUpdater);
}
@@ -2258,11 +2274,11 @@ private void updateGdsVersionForDataShare(Long dataShareId) {
private GdsPermission deletePrincipalFromAcl(RangerGdsObjectACL acl, String principalName, String principalType) {
final Map principalAcls;
- if (principalType.equalsIgnoreCase(RemoveRefType.USER.toString())) {
+ if (principalType.equalsIgnoreCase(REMOVE_REF_TYPE.USER.toString())) {
principalAcls = acl.getUsers();
- } else if (principalType.equalsIgnoreCase(RemoveRefType.GROUP.toString())) {
+ } else if (principalType.equalsIgnoreCase(REMOVE_REF_TYPE.GROUP.toString())) {
principalAcls = acl.getGroups();
- } else if (principalType.equalsIgnoreCase(RemoveRefType.ROLE.toString())) {
+ } else if (principalType.equalsIgnoreCase(REMOVE_REF_TYPE.ROLE.toString())) {
principalAcls = acl.getRoles();
} else {
principalAcls = null;
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/KmsKeyMgr.java b/security-admin/src/main/java/org/apache/ranger/biz/KmsKeyMgr.java
index 939970849e..a8fb2942f1 100755
--- a/security-admin/src/main/java/org/apache/ranger/biz/KmsKeyMgr.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/KmsKeyMgr.java
@@ -72,10 +72,12 @@
@Component
public class KmsKeyMgr {
- static final String NAME_RULES = "hadoop.security.auth_to_local";
- static final String RANGER_AUTH_TYPE = "hadoop.security.authentication";
- static final String HOST_NAME = "ranger.service.host";
private static final Logger logger = LoggerFactory.getLogger(KmsKeyMgr.class);
+
+ static final String NAME_RULES = "hadoop.security.auth_to_local";
+ static final String RANGER_AUTH_TYPE = "hadoop.security.authentication";
+ static final String HOST_NAME = "ranger.service.host";
+
private static final String KMS_KEY_LIST_URI = "v1/keys/names"; //GET
private static final String KMS_ADD_KEY_URI = "v1/keys"; //POST
private static final String KMS_ROLL_KEY_URI = "v1/key/${alias}"; //POST
@@ -89,6 +91,7 @@ public class KmsKeyMgr {
private static final String ADMIN_USER_KEYTAB = "ranger.admin.kerberos.keytab";
private static final Map providerList = new HashMap<>();
private static int nextProvider;
+
@Autowired
ServiceDBStore svcStore;
@@ -104,31 +107,36 @@ public class KmsKeyMgr {
@Autowired
RangerBizUtil rangerBizUtil;
- @SuppressWarnings("unchecked")
public VXKmsKeyList searchKeys(HttpServletRequest request, String repoName) throws Exception {
String[] providers = null;
+
try {
providers = getKMSURL(repoName);
} catch (Exception e) {
logger.error("getKey({}) failed", repoName, e);
}
+
List vXKeys = new ArrayList<>();
VXKmsKeyList vxKmsKeyList = new VXKmsKeyList();
- List keys = null;
String connProvider = null;
boolean isKerberos = false;
+
try {
isKerberos = checkKerberos();
} catch (Exception e1) {
logger.error("checkKerberos({}) failed", repoName, e1);
}
+
if (providers != null) {
for (int i = 0; i < providers.length; i++) {
Client c = getClient();
String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId());
String keyLists = KMS_KEY_LIST_URI.replaceAll(Pattern.quote("${userName}"), currentUserLoginId);
+
connProvider = providers[i];
+
String uri = providers[i] + (providers[i].endsWith("/") ? keyLists : ("/" + keyLists));
+
if (!isKerberos) {
uri = uri.concat("?user.name=" + currentUserLoginId);
} else {
@@ -136,32 +144,39 @@ public VXKmsKeyList searchKeys(HttpServletRequest request, String repoName) thro
}
final WebResource r = c.resource(uri);
+
try {
- String response = null;
+ String response;
+
if (!isKerberos) {
response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class);
} else {
Subject sub = getSubjectForKerberos(repoName);
- response = Subject.doAs(sub, new PrivilegedAction() {
- @Override
- public String run() {
- return r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class);
- }
- });
+
+ response = Subject.doAs(sub, (PrivilegedAction) () -> r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class));
}
logger.debug(" Search Key RESPONSE: [{}]", response);
- keys = JsonUtils.jsonToListString(response);
+
+ List keys = JsonUtils.jsonToListString(response);
+
Collections.sort(keys);
+
VXKmsKeyList vxKmsKeyList2 = new VXKmsKeyList();
List vXKeys2 = new ArrayList<>();
+
for (String name : keys) {
VXKmsKey key = new VXKmsKey();
+
key.setName(name);
+
vXKeys2.add(key);
}
+
vxKmsKeyList2.setVXKeys(vXKeys2);
+
vxKmsKeyList = getFilteredKeyList(request, vxKmsKeyList2);
+
break;
} catch (Exception e) {
if (e instanceof UniformInterfaceException || i == providers.length - 1) {
@@ -172,83 +187,100 @@ public String run() {
}
}
}
+
//details
if (vxKmsKeyList != null && vxKmsKeyList.getVXKeys() != null && !vxKmsKeyList.getVXKeys().isEmpty()) {
List lstKMSKey = vxKmsKeyList.getVXKeys();
int startIndex = restErrorUtil.parseInt(request.getParameter("startIndex"), 0, "Invalid value for parameter startIndex", MessageEnums.INVALID_INPUT_DATA, null, "startIndex");
+
startIndex = startIndex < 0 ? 0 : startIndex;
int pageSize = restErrorUtil.parseInt(request.getParameter("pageSize"), 0, "Invalid value for parameter pageSize", MessageEnums.INVALID_INPUT_DATA, null, "pageSize");
+
pageSize = pageSize < 0 ? 0 : pageSize;
vxKmsKeyList.setResultSize(lstKMSKey.size());
vxKmsKeyList.setTotalCount(lstKMSKey.size());
+
if ((startIndex + pageSize) <= lstKMSKey.size()) {
lstKMSKey = lstKMSKey.subList(startIndex, (startIndex + pageSize));
} else {
startIndex = startIndex >= lstKMSKey.size() ? 0 : startIndex;
lstKMSKey = lstKMSKey.subList(startIndex, lstKMSKey.size());
}
+
if (CollectionUtils.isNotEmpty(lstKMSKey)) {
for (VXKmsKey kmsKey : lstKMSKey) {
if (kmsKey != null) {
VXKmsKey key = getKeyFromUri(connProvider, kmsKey.getName(), isKerberos, repoName);
+
vXKeys.add(key);
}
}
}
+
vxKmsKeyList.setStartIndex(startIndex);
vxKmsKeyList.setPageSize(pageSize);
}
+
if (vxKmsKeyList != null) {
vxKmsKeyList.setVXKeys(vXKeys);
}
+
return vxKmsKeyList;
}
public VXKmsKey rolloverKey(String provider, VXKmsKey vXKey) throws Exception {
String[] providers = null;
+
rangerBizUtil.blockAuditorRoleUser();
+
try {
providers = getKMSURL(provider);
} catch (Exception e) {
logger.error("rolloverKey({}, {}) failed", provider, vXKey.getName(), e);
}
+
VXKmsKey ret = null;
boolean isKerberos = false;
+
try {
isKerberos = checkKerberos();
} catch (Exception e1) {
logger.error("checkKerberos({}) failed", provider, e1);
}
+
if (providers != null) {
for (int i = 0; i < providers.length; i++) {
Client c = getClient();
String rollRest = KMS_ROLL_KEY_URI.replaceAll(Pattern.quote("${alias}"), vXKey.getName());
String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId());
String uri = providers[i] + (providers[i].endsWith("/") ? rollRest : ("/" + rollRest));
+
if (!isKerberos) {
uri = uri.concat("?user.name=" + currentUserLoginId);
} else {
uri = uri.concat("?doAs=" + currentUserLoginId);
}
+
final WebResource r = c.resource(uri);
final String jsonString = JsonUtils.objectToJson(vXKey);
+
try {
- String response = null;
+ String response;
+
if (!isKerberos) {
response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString);
} else {
Subject sub = getSubjectForKerberos(provider);
- response = Subject.doAs(sub, new PrivilegedAction() {
- @Override
- public String run() {
- return r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString);
- }
- });
+
+ response = Subject.doAs(sub, (PrivilegedAction) () -> r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString));
}
+
logger.debug("Roll RESPONSE: [{}]", response);
+
ret = JsonUtils.jsonToObject(response, VXKmsKey.class);
+
break;
} catch (Exception e) {
if (e instanceof UniformInterfaceException || i == providers.length - 1) {
@@ -264,43 +296,48 @@ public String run() {
public void deleteKey(String provider, String name) throws Exception {
String[] providers = null;
+
rangerBizUtil.blockAuditorRoleUser();
+
try {
providers = getKMSURL(provider);
} catch (Exception e) {
logger.error("deleteKey({}, {}) failed", provider, name, e);
}
+
boolean isKerberos = false;
+
try {
isKerberos = checkKerberos();
} catch (Exception e1) {
logger.error("checkKerberos({}) failed", provider, e1);
}
+
if (providers != null) {
for (int i = 0; i < providers.length; i++) {
Client c = getClient();
String deleteRest = KMS_DELETE_KEY_URI.replaceAll(Pattern.quote("${alias}"), name);
String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId());
String uri = providers[i] + (providers[i].endsWith("/") ? deleteRest : ("/" + deleteRest));
+
if (!isKerberos) {
uri = uri.concat("?user.name=" + currentUserLoginId);
} else {
uri = uri.concat("?doAs=" + currentUserLoginId);
}
+
final WebResource r = c.resource(uri);
try {
- String response = null;
+ String response;
+
if (!isKerberos) {
response = r.delete(String.class);
} else {
Subject sub = getSubjectForKerberos(provider);
- response = Subject.doAs(sub, new PrivilegedAction() {
- @Override
- public String run() {
- return r.delete(String.class);
- }
- });
+
+ response = Subject.doAs(sub, (PrivilegedAction) () -> r.delete(String.class));
}
+
logger.debug("delete RESPONSE: [{}]", response);
break;
} catch (Exception e) {
@@ -316,46 +353,54 @@ public String run() {
public VXKmsKey createKey(String provider, VXKmsKey vXKey) throws Exception {
String[] providers = null;
+
rangerBizUtil.blockAuditorRoleUser();
+
try {
providers = getKMSURL(provider);
} catch (Exception e) {
logger.error("createKey({}, {}) failed", provider, vXKey.getName(), e);
}
+
VXKmsKey ret = null;
boolean isKerberos = false;
+
try {
isKerberos = checkKerberos();
} catch (Exception e1) {
logger.error("checkKerberos({}) failed", provider, e1);
}
+
if (providers != null) {
for (int i = 0; i < providers.length; i++) {
Client c = getClient();
String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId());
String uri = providers[i] + (providers[i].endsWith("/") ? KMS_ADD_KEY_URI : ("/" + KMS_ADD_KEY_URI));
+
if (!isKerberos) {
uri = uri.concat("?user.name=" + currentUserLoginId);
} else {
uri = uri.concat("?doAs=" + currentUserLoginId);
}
+
final WebResource r = c.resource(uri);
final String jsonString = JsonUtils.objectToJson(vXKey);
+
try {
- String response = null;
+ String response;
+
if (!isKerberos) {
response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString);
} else {
Subject sub = getSubjectForKerberos(provider);
- response = Subject.doAs(sub, new PrivilegedAction() {
- @Override
- public String run() {
- return r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString);
- }
- });
+
+ response = Subject.doAs(sub, (PrivilegedAction) () -> r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).post(String.class, jsonString));
}
+
logger.debug("Create RESPONSE: [{}]", response);
+
ret = JsonUtils.jsonToObject(response, VXKmsKey.class);
+
return ret;
} catch (Exception e) {
if (e instanceof UniformInterfaceException || i == providers.length - 1) {
@@ -366,57 +411,66 @@ public String run() {
}
}
}
+
return ret;
}
public VXKmsKey getKey(String provider, String name) throws Exception {
String[] providers = null;
+
try {
providers = getKMSURL(provider);
} catch (Exception e) {
logger.error("getKey({}, {}) failed", provider, name, e);
}
+
boolean isKerberos = false;
+
try {
isKerberos = checkKerberos();
} catch (Exception e1) {
logger.error("checkKerberos({}) failed", provider, e1);
}
+
if (providers != null) {
for (int i = 0; i < providers.length; i++) {
Client c = getClient();
String keyRest = KMS_KEY_METADATA_URI.replaceAll(Pattern.quote("${alias}"), name);
String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId());
String uri = providers[i] + (providers[i].endsWith("/") ? keyRest : ("/" + keyRest));
+
if (!isKerberos) {
uri = uri.concat("?user.name=" + currentUserLoginId);
} else {
uri = uri.concat("?doAs=" + currentUserLoginId);
}
+
final WebResource r = c.resource(uri);
+
try {
- String response = null;
+ String response;
+
if (!isKerberos) {
response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class);
} else {
Subject sub = getSubjectForKerberos(provider);
- response = Subject.doAs(sub, new PrivilegedAction() {
- @Override
- public String run() {
- return r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class);
- }
- });
+
+ response = Subject.doAs(sub, (PrivilegedAction) () -> r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class));
}
+
logger.debug("RESPONSE: [{}]", response);
- VXKmsKey key = JsonUtils.jsonToObject(response, VXKmsKey.class);
- return key;
+
+ return JsonUtils.jsonToObject(response, VXKmsKey.class);
} catch (Exception e) {
if (e instanceof UniformInterfaceException || i == providers.length - 1) {
throw e;
+ } else {
+ continue;
}
}
}
}
+
return null;
}
@@ -425,31 +479,32 @@ public VXKmsKey getKeyFromUri(String provider, String name, boolean isKerberos,
String keyRest = KMS_KEY_METADATA_URI.replaceAll(Pattern.quote("${alias}"), name);
String currentUserLoginId = StringUtil.getUTFEncodedString(ContextUtil.getCurrentUserLoginId());
String uri = provider + (provider.endsWith("/") ? keyRest : ("/" + keyRest));
+
if (!isKerberos) {
uri = uri.concat("?user.name=" + currentUserLoginId);
} else {
uri = uri.concat("?doAs=" + currentUserLoginId);
}
- final WebResource r = c.resource(uri);
- String response = null;
+
+ final WebResource r = c.resource(uri);
+ String response;
+
if (!isKerberos) {
response = r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class);
} else {
Subject sub = getSubjectForKerberos(repoName);
- response = Subject.doAs(sub, new PrivilegedAction() {
- @Override
- public String run() {
- return r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class);
- }
- });
+
+ response = Subject.doAs(sub, (PrivilegedAction) () -> r.accept(MediaType.APPLICATION_JSON_TYPE).type(MediaType.APPLICATION_JSON_TYPE).get(String.class));
}
+
logger.debug("RESPONSE: [{}]", response);
- VXKmsKey key = JsonUtils.jsonToObject(response, VXKmsKey.class);
- return key;
+
+ return JsonUtils.jsonToObject(response, VXKmsKey.class);
}
public VXKmsKeyList getFilteredKeyList(HttpServletRequest request, VXKmsKeyList vXKmsKeyList) {
List sortFields = new ArrayList<>();
+
sortFields.add(new SortField(KeySearchFilter.KEY_NAME, KeySearchFilter.KEY_NAME));
KeySearchFilter filter = getKeySearchFilter(request, sortFields);
@@ -459,33 +514,40 @@ public VXKmsKeyList getFilteredKeyList(HttpServletRequest request, VXKmsKeyList
if (pred != null) {
CollectionUtils.filter(vXKmsKeyList.getVXKeys(), pred);
}
+
return vXKmsKeyList;
}
private String[] getKMSURL(String name) throws Exception {
- String[] providers = null;
- RangerService rangerService = null;
+ String[] providers;
+
try {
- rangerService = svcStore.getServiceByName(name);
+ RangerService rangerService = svcStore.getServiceByName(name);
+
if (rangerService != null) {
String kmsUrl = rangerService.getConfigs().get(KMS_URL_CONFIG);
String dbKmsUrl = kmsUrl;
+
if (providerList.containsKey(kmsUrl)) {
kmsUrl = providerList.get(kmsUrl);
} else {
providerList.put(kmsUrl, kmsUrl);
}
+
providers = createProvider(dbKmsUrl, kmsUrl);
} else {
throw new Exception("Service " + name + " not found");
}
} catch (Exception excp) {
logger.error("getServiceByName({}) failed", name, excp);
+
throw new Exception("getServiceByName(" + name + ") failed", excp);
}
+
if (providers == null) {
throw new Exception("Providers for service " + name + " not found");
}
+
return providers;
}
@@ -493,62 +555,78 @@ private String[] createProvider(String dbKmsUrl, String uri) throws IOException,
URI providerUri = new URI(uri);
URL origUrl = new URL(extractKMSPath(providerUri).toString());
String authority = origUrl.getAuthority();
- //check for ';' which delimits the backup hosts
+
+ // check for ';' which delimits the backup hosts
if (StringUtils.isEmpty(authority)) {
throw new IOException("No valid authority in kms uri [" + origUrl + "]");
}
+
// Check if port is present in authority
// In the current scheme, all hosts have to run on the same port
int port = -1;
String hostsPart = authority;
+
if (authority.contains(":")) {
String[] t = authority.split(":");
+
try {
port = Integer.parseInt(t[1]);
} catch (Exception e) {
throw new IOException("Could not parse port in kms uri [" + origUrl + "]");
}
+
hostsPart = t[0];
}
+
return createProvider(dbKmsUrl, providerUri, origUrl, port, hostsPart);
}
- private static Path extractKMSPath(URI uri) throws IOException {
+ private static Path extractKMSPath(URI uri) {
return ProviderUtils.unnestUri(uri);
}
private String[] createProvider(String dbkmsUrl, URI providerUri, URL origUrl, int port, String hostsPart) throws IOException {
String[] hosts = hostsPart.split(";");
String[] providers = new String[hosts.length];
+
if (hosts.length == 1) {
providers[0] = origUrl.toString();
} else {
String providerNext = providerUri.getScheme() + "://" + origUrl.getProtocol() + "@";
+
for (int i = nextProvider; i < hosts.length; i++) {
providerNext = providerNext + hosts[i];
+
if (i != (hosts.length - 1)) {
providerNext = providerNext + ";";
}
}
+
for (int i = 0; i < nextProvider && i < hosts.length; i++) {
providerNext = providerNext + ";" + hosts[i];
}
+
if (nextProvider != hosts.length - 1) {
nextProvider = nextProvider + 1;
} else {
nextProvider = 0;
}
+
providerNext = providerNext + ":" + port + origUrl.getPath();
+
providerList.put(dbkmsUrl, providerNext);
+
for (int i = 0; i < hosts.length; i++) {
try {
String url = origUrl.getProtocol() + "://" + hosts[i] + ":" + port + origUrl.getPath();
+
providers[i] = new URI(url).toString();
} catch (URISyntaxException e) {
throw new IOException("Could not Prase KMS URL..", e);
}
}
}
+
return providers;
}
@@ -556,14 +634,18 @@ private Subject getSubjectForKerberos(String provider) throws Exception {
String userName = getKMSUserName(provider);
String password = getKMSPassword(provider);
String nameRules = PropertiesUtil.getProperty(NAME_RULES);
+
if (StringUtils.isEmpty(nameRules)) {
KerberosName.setRules("DEFAULT");
+
nameRules = "DEFAULT";
} else {
KerberosName.setRules(nameRules);
}
- Subject sub = new Subject();
+
+ Subject sub;
String rangerPrincipal = SecureClientLogin.getPrincipal(PropertiesUtil.getProperty(ADMIN_USER_PRINCIPAL), PropertiesUtil.getProperty(HOST_NAME));
+
if (checkKerberos()) {
if (SecureClientLogin.isKerberosCredentialExists(rangerPrincipal, PropertiesUtil.getProperty(ADMIN_USER_KEYTAB))) {
sub = SecureClientLogin.loginUserFromKeytab(rangerPrincipal, PropertiesUtil.getProperty(ADMIN_USER_KEYTAB), nameRules);
@@ -573,6 +655,7 @@ private Subject getSubjectForKerberos(String provider) throws Exception {
} else {
sub = SecureClientLogin.login(userName);
}
+
return sub;
}
@@ -580,26 +663,26 @@ private String getKMSPassword(String srvName) throws Exception {
XXService rangerService = rangerDaoManagerBase.getXXService().findByName(srvName);
XXServiceConfigMap xxConfigMap = rangerDaoManagerBase.getXXServiceConfigMap().findByServiceAndConfigKey(rangerService.getId(), KMS_PASSWORD);
String encryptedPwd = xxConfigMap.getConfigvalue();
- String pwd = PasswordUtils.decryptPassword(encryptedPwd);
- return pwd;
+
+ return PasswordUtils.decryptPassword(encryptedPwd);
}
private String getKMSUserName(String srvName) throws Exception {
- RangerService rangerService = null;
- rangerService = svcStore.getServiceByName(srvName);
+ RangerService rangerService = svcStore.getServiceByName(srvName);
+
return rangerService.getConfigs().get(KMS_USERNAME);
}
- private boolean checkKerberos() throws Exception {
+ private boolean checkKerberos() {
return KERBEROS_TYPE.equalsIgnoreCase(PropertiesUtil.getProperty(RANGER_AUTH_TYPE, "simple"));
}
private synchronized Client getClient() {
- Client ret = null;
ClientConfig cc = new DefaultClientConfig();
+
cc.getProperties().put(ClientConfig.PROPERTY_FOLLOW_REDIRECTS, true);
- ret = Client.create(cc);
- return ret;
+
+ return Client.create(cc);
}
private Predicate getPredicate(KeySearchFilter filter) {
@@ -611,9 +694,7 @@ private Predicate getPredicate(KeySearchFilter filter) {
addPredicateForKeyName(filter.getParam(KeySearchFilter.KEY_NAME), predicates);
- Predicate ret = CollectionUtils.isEmpty(predicates) ? null : PredicateUtils.allPredicate(predicates);
-
- return ret;
+ return CollectionUtils.isEmpty(predicates) ? null : PredicateUtils.allPredicate(predicates);
}
private Predicate addPredicateForKeyName(final String name, List predicates) {
@@ -621,28 +702,26 @@ private Predicate addPredicateForKeyName(final String name, List pred
return null;
}
- Predicate ret = new Predicate() {
- @Override
- public boolean evaluate(Object object) {
- if (object == null) {
- return false;
- }
+ Predicate ret = object -> {
+ if (object == null) {
+ return false;
+ }
- boolean ret = false;
+ boolean ret1 = false;
- if (object instanceof VXKmsKey) {
- VXKmsKey vXKmsKey = (VXKmsKey) object;
- if (StringUtils.isEmpty(vXKmsKey.getName())) {
- ret = true;
- } else {
- ret = vXKmsKey.getName().contains(name);
- }
+ if (object instanceof VXKmsKey) {
+ VXKmsKey vXKmsKey = (VXKmsKey) object;
+
+ if (StringUtils.isEmpty(vXKmsKey.getName())) {
+ ret1 = true;
} else {
- ret = true;
+ ret1 = vXKmsKey.getName().contains(name);
}
-
- return ret;
+ } else {
+ ret1 = true;
}
+
+ return ret1;
};
if (predicates != null) {
@@ -656,6 +735,7 @@ private KeySearchFilter getKeySearchFilter(HttpServletRequest request, List sortFields) {
int startIndex = restErrorUtil.parseInt(request.getParameter(KeySearchFilter.START_INDEX), 0, "Invalid value for parameter startIndex", MessageEnums.INVALID_INPUT_DATA, null, KeySearchFilter.START_INDEX);
+
ret.setStartIndex(startIndex);
int pageSize = restErrorUtil.parseInt(request.getParameter(KeySearchFilter.PAGE_SIZE), configUtil.getDefaultMaxRows(), "Invalid value for parameter pageSize", MessageEnums.INVALID_INPUT_DATA, null, KeySearchFilter.PAGE_SIZE);
+
ret.setMaxRows(pageSize);
ret.setGetCount(restErrorUtil.parseBoolean(request.getParameter("getCount"), true));
+
String sortBy = restErrorUtil.validateString(request.getParameter(KeySearchFilter.SORT_BY), StringUtil.VALIDATION_ALPHA, "Invalid value for parameter sortBy", MessageEnums.INVALID_INPUT_DATA, null, KeySearchFilter.SORT_BY);
boolean sortSet = false;
+
if (!StringUtils.isEmpty(sortBy)) {
for (SortField sortField : sortFields) {
if (sortField.getParamName().equalsIgnoreCase(sortBy)) {
ret.setSortBy(sortField.getParamName());
+
String sortType = restErrorUtil.validateString(request.getParameter("sortType"), StringUtil.VALIDATION_ALPHA, "Invalid value for parameter sortType", MessageEnums.INVALID_INPUT_DATA, null, "sortType");
+
ret.setSortType(sortType);
+
sortSet = true;
+
break;
}
}
@@ -696,6 +786,7 @@ private KeySearchFilter extractCommonCriteriasForFilter(HttpServletRequest reque
if (ret.getParams() == null) {
ret.setParams(new HashMap<>());
}
+
return ret;
}
}
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/PolicyRefUpdater.java b/security-admin/src/main/java/org/apache/ranger/biz/PolicyRefUpdater.java
index 3b00f1d1d4..4ed8ef9105 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/PolicyRefUpdater.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/PolicyRefUpdater.java
@@ -70,22 +70,30 @@
@Component
public class PolicyRefUpdater {
private static final Logger LOG = LoggerFactory.getLogger(PolicyRefUpdater.class);
+
@Autowired
- RangerDaoManager daoMgr;
+ RangerDaoManager daoMgr;
+
@Autowired
- RangerAuditFields> rangerAuditFields;
+ RangerAuditFields> rangerAuditFields;
+
@Autowired
- XUserMgr xUserMgr;
+ XUserMgr xUserMgr;
+
@Autowired
- RoleDBStore roleStore;
+ RoleDBStore roleStore;
+
@Autowired
- RangerBizUtil rangerBizUtil;
+ RangerBizUtil rangerBizUtil;
+
@Autowired
- XGroupService xGroupService;
+ XGroupService xGroupService;
+
@Autowired
RangerTransactionSynchronizationAdapter rangerTransactionSynchronizationAdapter;
+
@Autowired
- RESTErrorUtil restErrorUtil;
+ RESTErrorUtil restErrorUtil;
public static List> getAllPolicyItems(RangerPolicy policy) {
List> ret = new ArrayList<>();
@@ -134,6 +142,7 @@ public void createNewPolMappingForRefTable(RangerPolicy policy, XXPolicy xPolicy
boolean oldBulkMode = RangerBizUtil.isBulkMode();
List rangerPolicyConditions = policy.getConditions();
+
if (CollectionUtils.isNotEmpty(rangerPolicyConditions)) {
for (RangerPolicy.RangerPolicyItemCondition condition : rangerPolicyConditions) {
conditionTypes.add(condition.getType());
@@ -171,6 +180,7 @@ public void createNewPolMappingForRefTable(RangerPolicy policy, XXPolicy xPolicy
}
List xPolResources = new ArrayList<>();
+
for (String resource : resourceNames) {
XXResourceDef xResDef = daoMgr.getXXResourceDef().findByNameAndPolicyId(resource, policy.getId());
@@ -186,32 +196,40 @@ public void createNewPolMappingForRefTable(RangerPolicy policy, XXPolicy xPolicy
xPolResources.add(xPolRes);
}
+
daoMgr.getXXPolicyRefResource().batchCreate(xPolResources);
if (createPrincipalsIfAbsent && !rangerBizUtil.checkAdminAccess()) {
- LOG.warn("policy={} createPrincipalIfAbsent=true, but current user does not have admin privileges!", policy.getName());
+ LOG.warn("policy={}: createPrincipalIfAbsent=true, but current user does not have admin privileges!", policy.getName());
createPrincipalsIfAbsent = false;
}
List xPolRoles = new ArrayList<>();
+
for (String role : roleNames) {
if (StringUtils.isBlank(role)) {
continue;
}
- PolicyPrincipalAssociator associator = new PolicyPrincipalAssociator(PrincipalType.ROLE, role, xPolicy);
+
+ PolicyPrincipalAssociator associator = new PolicyPrincipalAssociator(PRINCIPAL_TYPE.ROLE, role, xPolicy);
+
if (!associator.doAssociate(false)) {
if (createPrincipalsIfAbsent) {
rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(associator);
} else {
VXResponse gjResponse = new VXResponse();
+
gjResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST);
gjResponse.setMsgDesc("Operation denied. Role name: " + role + " specified in policy does not exist in ranger admin.");
+
throw restErrorUtil.generateRESTException(gjResponse);
}
}
}
+
RangerBizUtil.setBulkMode(oldBulkMode);
+
daoMgr.getXXPolicyRefRole().batchCreate(xPolRoles);
for (String group : groupNames) {
@@ -219,14 +237,17 @@ public void createNewPolMappingForRefTable(RangerPolicy policy, XXPolicy xPolicy
continue;
}
- PolicyPrincipalAssociator associator = new PolicyPrincipalAssociator(PrincipalType.GROUP, group, xPolicy);
+ PolicyPrincipalAssociator associator = new PolicyPrincipalAssociator(PRINCIPAL_TYPE.GROUP, group, xPolicy);
+
if (!associator.doAssociate(false)) {
if (createPrincipalsIfAbsent) {
rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(associator);
} else {
VXResponse gjResponse = new VXResponse();
+
gjResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST);
gjResponse.setMsgDesc("Operation denied. Group name: " + group + " specified in policy does not exist in ranger admin.");
+
throw restErrorUtil.generateRESTException(gjResponse);
}
}
@@ -236,14 +257,18 @@ public void createNewPolMappingForRefTable(RangerPolicy policy, XXPolicy xPolicy
if (StringUtils.isBlank(user)) {
continue;
}
- PolicyPrincipalAssociator associator = new PolicyPrincipalAssociator(PrincipalType.USER, user, xPolicy);
+
+ PolicyPrincipalAssociator associator = new PolicyPrincipalAssociator(PRINCIPAL_TYPE.USER, user, xPolicy);
+
if (!associator.doAssociate(false)) {
if (createPrincipalsIfAbsent) {
rangerTransactionSynchronizationAdapter.executeOnTransactionCommit(associator);
} else {
VXResponse gjResponse = new VXResponse();
+
gjResponse.setStatusCode(HttpServletResponse.SC_BAD_REQUEST);
gjResponse.setMsgDesc("Operation denied. User name: " + user + " specified in policy does not exist in ranger admin.");
+
throw restErrorUtil.generateRESTException(gjResponse);
}
}
@@ -269,9 +294,11 @@ public void createNewPolMappingForRefTable(RangerPolicy policy, XXPolicy xPolicy
xPolAccesses.add(xPolAccess);
}
+
daoMgr.getXXPolicyRefAccessType().batchCreate(xPolAccesses);
List xPolConds = new ArrayList<>();
+
for (String condition : conditionTypes) {
XXPolicyConditionDef xPolCondDef = daoMgr.getXXPolicyConditionDef().findByServiceDefIdAndName(xServiceDef.getId(), condition);
@@ -291,9 +318,11 @@ public void createNewPolMappingForRefTable(RangerPolicy policy, XXPolicy xPolicy
xPolConds.add(xPolCond);
}
+
daoMgr.getXXPolicyRefCondition().batchCreate(xPolConds);
List xxDataMaskInfos = new ArrayList<>();
+
for (String dataMaskType : dataMaskTypes) {
XXDataMaskTypeDef dataMaskDef = daoMgr.getXXDataMaskTypeDef().findByNameAndServiceId(dataMaskType, xPolicy.getService());
@@ -309,6 +338,7 @@ public void createNewPolMappingForRefTable(RangerPolicy policy, XXPolicy xPolicy
xxDataMaskInfos.add(xxDataMaskInfo);
}
+
daoMgr.getXXPolicyRefDataMaskType().batchCreate(xxDataMaskInfos);
}
@@ -330,16 +360,14 @@ public Boolean cleanupRefTables(RangerPolicy policy) {
return true;
}
- public enum PrincipalType {
- USER, GROUP, ROLE
- }
+ public enum PRINCIPAL_TYPE { USER, GROUP, ROLE }
private class PolicyPrincipalAssociator implements Runnable {
- final PrincipalType type;
- final String name;
- final XXPolicy xPolicy;
+ final PRINCIPAL_TYPE type;
+ final String name;
+ final XXPolicy xPolicy;
- public PolicyPrincipalAssociator(PrincipalType type, String name, XXPolicy xPolicy) {
+ public PolicyPrincipalAssociator(PRINCIPAL_TYPE type, String name, XXPolicy xPolicy) {
this.type = type;
this.name = name;
this.xPolicy = xPolicy;
@@ -356,18 +384,22 @@ public void run() {
boolean doAssociate(boolean isAdmin) {
LOG.debug("===> PolicyPrincipalAssociator.doAssociate({})", isAdmin);
+
final boolean ret;
Long id = createOrGetPrincipal(isAdmin);
+
if (id != null) {
// associate with policy
createPolicyAssociation(id, name);
+
ret = true;
} else {
ret = false;
}
- LOG.debug("<=== PolicyPrincipalAssociator.doAssociate({}) : ", isAdmin, ret);
+ LOG.debug("<=== PolicyPrincipalAssociator.doAssociate({}) : {}", isAdmin, ret);
+
return ret;
}
@@ -379,6 +411,7 @@ private Long createOrGetPrincipal(final boolean createIfAbsent) {
switch (type) {
case USER: {
XXUser xUser = daoMgr.getXXUser().findByUserName(name);
+
if (xUser != null) {
ret = xUser.getId();
} else {
@@ -402,6 +435,7 @@ private Long createOrGetPrincipal(final boolean createIfAbsent) {
break;
case ROLE: {
XXRole xRole = daoMgr.getXXRole().findByRoleName(name);
+
if (xRole != null) {
ret = xRole.getId();
} else {
@@ -415,7 +449,9 @@ private Long createOrGetPrincipal(final boolean createIfAbsent) {
default:
break;
}
+
LOG.debug("<=== PolicyPrincipalAssociator.createOrGetPrincipal({}) : {}", createIfAbsent, ret);
+
return ret;
}
@@ -446,10 +482,13 @@ private Long createPrincipal(String user) {
case GROUP: {
// Create group
VXGroup vxGroup = new VXGroup();
+
vxGroup.setName(name);
vxGroup.setDescription(name);
vxGroup.setGroupSource(RangerCommonEnums.GROUP_EXTERNAL);
+
VXGroup vXGroup = xGroupService.createXGroupWithOutLogin(vxGroup);
+
if (vXGroup != null) {
xGroupService.createTransactionLog(vXGroup, null, OPERATION_CREATE_CONTEXT, xPolicy.getAddedByUserId());
@@ -461,6 +500,7 @@ private Long createPrincipal(String user) {
try {
RangerRole rRole = new RangerRole(name, null, null, null, null);
RangerRole createdRole = roleStore.createRole(rRole, false);
+
ret = createdRole.getId();
} catch (Exception e) {
// Ignore
@@ -470,12 +510,15 @@ private Long createPrincipal(String user) {
default:
break;
}
- LOG.debug("<=== PolicyPrincipalAssociator.createPrincipal(type={}, name={}) :{} ", type.name(), name, ret);
+
+ LOG.debug("<=== PolicyPrincipalAssociator.createPrincipal(type={}, name={}) : {}", type.name(), name, ret);
+
return ret;
}
private void createPolicyAssociation(Long id, String name) {
LOG.debug("===> PolicyPrincipalAssociator.createPolicyAssociation(policyId={}, type={}, name={}, id={})", xPolicy.getId(), type.name(), name, id);
+
switch (type) {
case USER: {
XXPolicyRefUser xPolUser = rangerAuditFields.populateAuditFields(new XXPolicyRefUser(), xPolicy);
@@ -483,6 +526,7 @@ private void createPolicyAssociation(Long id, String name) {
xPolUser.setPolicyId(xPolicy.getId());
xPolUser.setUserId(id);
xPolUser.setUserName(name);
+
daoMgr.getXXPolicyRefUser().create(xPolUser);
}
break;
@@ -492,6 +536,7 @@ private void createPolicyAssociation(Long id, String name) {
xPolGroup.setPolicyId(xPolicy.getId());
xPolGroup.setGroupId(id);
xPolGroup.setGroupName(name);
+
daoMgr.getXXPolicyRefGroup().create(xPolGroup);
}
break;
@@ -501,12 +546,14 @@ private void createPolicyAssociation(Long id, String name) {
xPolRole.setPolicyId(xPolicy.getId());
xPolRole.setRoleId(id);
xPolRole.setRoleName(name);
+
daoMgr.getXXPolicyRefRole().create(xPolRole);
}
break;
default:
break;
}
+
LOG.debug("<=== PolicyPrincipalAssociator.createPolicyAssociation(policyId={}, type={}, name={}, id={})", xPolicy.getId(), type.name(), name, id);
}
}
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java
index 1d6c5c1ce6..f697d9ce5b 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerBizUtil.java
@@ -75,13 +75,14 @@
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
@Component
public class RangerBizUtil {
+ private static final Logger logger = LoggerFactory.getLogger(RangerBizUtil.class);
+
public static final String AUDIT_STORE_RDBMS = "DB";
public static final String AUDIT_STORE_SOLR = "solr";
public static final String AUDIT_STORE_ELASTIC_SEARCH = "elasticSearch";
@@ -89,32 +90,42 @@ public class RangerBizUtil {
public static final boolean BATCH_CLEAR_ENABLED = PropertiesUtil.getBooleanProperty("ranger.jpa.jdbc.batch-clear.enable", true);
public static final int POLICY_BATCH_SIZE = PropertiesUtil.getIntProperty("ranger.jpa.jdbc.batch-clear.size", 10);
public static final int BATCH_PERSIST_SIZE = PropertiesUtil.getIntProperty("ranger.jpa.jdbc.batch-persist.size", 500);
- private static final Logger logger = LoggerFactory.getLogger(RangerBizUtil.class);
- private static final String PATH_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrst0123456789-_.";
- private static final char[] PATH_CHAR_SET = PATH_CHARS.toCharArray();
- private static final int PATH_CHAR_SET_LEN = PATH_CHAR_SET.length;
- static String fileSeparator = PropertiesUtil.getProperty("ranger.file.separator", "/");
- private final boolean allowUnauthenticatedAccessInSecureEnvironment;
- private final boolean allowUnauthenticatedDownloadAccessInSecureEnvironment;
- private final Class>[] groupEditableClassesList = {};
- private final int maxFirstNameLength;
- private final SecureRandom random;
+
+ private static final String PATH_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrst0123456789-_.";
+
+ static String fileSeparator = PropertiesUtil.getProperty("ranger.file.separator", "/");
+
+ private static final char[] PATH_CHAR_SET = PATH_CHARS.toCharArray();
+ private static final int PATH_CHAR_SET_LEN = PATH_CHAR_SET.length;
+
@Autowired
- RESTErrorUtil restErrorUtil;
+ RESTErrorUtil restErrorUtil;
+
@Autowired
RangerDaoManager daoManager;
+
@Autowired
- StringUtil stringUtil;
+ StringUtil stringUtil;
+
@Autowired
- UserMgr userMgr;
+ UserMgr userMgr;
+
@Autowired
- XUserService xUserService;
+ XUserService xUserService;
+
@Autowired
- GUIDUtil guidUtil;
+ GUIDUtil guidUtil;
+
+ private final boolean allowUnauthenticatedAccessInSecureEnvironment;
+ private final boolean allowUnauthenticatedDownloadAccessInSecureEnvironment;
+ private final Class>[] groupEditableClassesList = {};
+ private final int maxFirstNameLength;
+ private final SecureRandom random;
+
Set> groupEditableClasses;
int maxDisplayNameLength = 150;
boolean enableResourceAccessControl;
- String auditDBType = AUDIT_STORE_RDBMS;
+ String auditDBType = AUDIT_STORE_RDBMS;
public RangerBizUtil() {
RangerAdminConfig config = RangerAdminConfig.getInstance();
@@ -129,8 +140,10 @@ public RangerBizUtil() {
enableResourceAccessControl = PropertiesUtil.getBooleanProperty("ranger.resource.accessControl.enabled", true);
auditDBType = PropertiesUtil.getProperty("ranger.audit.source.type", auditDBType).toLowerCase();
+
logger.info("java.library.path is {}", System.getProperty("java.library.path"));
logger.info("Audit datasource is {}", auditDBType);
+
random = new SecureRandom();
}
@@ -148,11 +161,16 @@ public static boolean areAllEqual(int checkValue, int... otherValues) {
return false;
}
}
+
return true;
}
public static int getDBFlavor() {
- String[] propertyNames = {"xa.db.flavor", "ranger.jpa.jdbc.dialect", "ranger.jpa.jdbc.url", "ranger.jpa.jdbc.driver"};
+ String[] propertyNames = {"xa.db.flavor",
+ "ranger.jpa.jdbc.dialect",
+ "ranger.jpa.jdbc.url",
+ "ranger.jpa.jdbc.driver"
+ };
for (String propertyName : propertyNames) {
String propertyValue = PropertiesUtil.getProperty(propertyName);
@@ -176,7 +194,7 @@ public static int getDBFlavor() {
} else if (StringUtils.containsIgnoreCase(propertyValue, "sqla")) {
return AppConstants.DB_FLAVOR_SQLANYWHERE;
} else {
- logger.debug("DB Flavor could not be determined from property - {} = {}", propertyName, propertyValue);
+ logger.debug("DB Flavor could not be determined from property - {}={}", propertyName, propertyValue);
}
}
@@ -248,9 +266,11 @@ public static boolean setBulkMode(boolean val) {
// Access control methods
public void checkSystemAdminAccess() {
UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
+
if (currentUserSession != null && currentUserSession.isUserAdmin()) {
return;
}
+
throw restErrorUtil.create403RESTException("Only System Administrators can add accounts");
}
@@ -265,12 +285,15 @@ public String generatePublicName(VXPortalUser userProfile, XXPortalUser gjUser)
public String generatePublicName(String firstName, String lastName) {
String publicName = null;
String fName = firstName;
+
if (firstName.length() > maxFirstNameLength) {
fName = firstName.substring(0, maxFirstNameLength - (1 + 3)) + "...";
}
- if (lastName != null && lastName.length() > 0) {
+
+ if (lastName != null && !lastName.isEmpty()) {
publicName = fName + " " + lastName.charAt(0) + ".";
}
+
return publicName;
}
@@ -280,9 +303,12 @@ public VXStringList mapStringListToVStringList(List stringList) {
}
List vStringList = new ArrayList<>();
+
for (String str : stringList) {
VXString vXString = new VXString();
+
vXString.setValue(str);
+
vStringList.add(vXString);
}
@@ -298,21 +324,26 @@ public VXStringList mapStringListToVStringList(List stringList) {
*/
public VXResponse hasPermission(VXResource vXResource, int permission) {
VXResponse vXResponse = new VXResponse();
+
if (!enableResourceAccessControl) {
logger.debug("Resource Access Control is disabled !!!");
+
return vXResponse;
}
if (vXResource == null) {
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
vXResponse.setMsgDesc("Please provide valid policy.");
+
return vXResponse;
}
String resourceNames = vXResource.getName();
+
if (stringUtil.isEmpty(resourceNames)) {
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
vXResponse.setMsgDesc("Please provide valid policy.");
+
return vXResponse;
}
@@ -332,78 +363,107 @@ public VXResponse hasPermission(VXResource vXResource, int permission) {
if (assetType == AppConstants.ASSET_HIVE) {
String[] requestResNameList = resourceNames.split(",");
+
if (stringUtil.isEmpty(vXResource.getUdfs())) {
int reqTableType = vXResource.getTableType();
int reqColumnType = vXResource.getColumnType();
+
for (String resourceName : requestResNameList) {
boolean matchFound = matchHivePolicy(resourceName, xResourceList, xUserId, permission, reqTableType, reqColumnType, false);
+
if (!matchFound) {
- vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
+ vXResponse.setMsgDesc("You're not permitted to perform the action for resource path : " + resourceName);
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
+
return vXResponse;
}
}
} else {
for (String resourceName : requestResNameList) {
boolean matchFound = matchHivePolicy(resourceName, xResourceList, xUserId, permission);
+
if (!matchFound) {
- vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
+ vXResponse.setMsgDesc("You're not permitted to perform the action for resource path : " + resourceName);
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
+
return vXResponse;
}
}
}
+
vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
+
return vXResponse;
} else if (assetType == AppConstants.ASSET_HBASE) {
String[] requestResNameList = resourceNames.split(",");
+
for (String resourceName : requestResNameList) {
boolean matchFound = matchHbasePolicy(resourceName, xResourceList, vXResponse, xUserId, permission);
+
if (!matchFound) {
vXResponse.setMsgDesc("You're not permitted to perform the action for resource path : " + resourceName);
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
+
return vXResponse;
}
}
+
vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
+
return vXResponse;
} else if (assetType == AppConstants.ASSET_HDFS) {
String[] requestResNameList = resourceNames.split(",");
+
for (String resourceName : requestResNameList) {
boolean matchFound = matchHdfsPolicy(resourceName, xResourceList, xUserId, permission);
+
if (!matchFound) {
- vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
+ vXResponse.setMsgDesc("You're not permitted to perform the action for resource path : " + resourceName);
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
+
return vXResponse;
}
}
+
vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
+
return vXResponse;
} else if (assetType == AppConstants.ASSET_KNOX) {
String[] requestResNameList = resourceNames.split(",");
+
for (String resourceName : requestResNameList) {
boolean matchFound = matchKnoxPolicy(resourceName, xResourceList, xUserId, permission);
+
if (!matchFound) {
- vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
+ vXResponse.setMsgDesc("You're not permitted to perform the action for resource path : " + resourceName);
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
+
return vXResponse;
}
}
+
vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
+
return vXResponse;
} else if (assetType == AppConstants.ASSET_STORM) {
String[] requestResNameList = resourceNames.split(",");
+
for (String resourceName : requestResNameList) {
boolean matchFound = matchStormPolicy(resourceName, xResourceList, xUserId, permission);
+
if (!matchFound) {
- vXResponse.setMsgDesc("You're not permitted to perform " + "the action for resource path : " + resourceName);
+ vXResponse.setMsgDesc("You're not permitted to perform the action for resource path : " + resourceName);
vXResponse.setStatusCode(VXResponse.STATUS_ERROR);
+
return vXResponse;
}
}
+
vXResponse.setStatusCode(VXResponse.STATUS_SUCCESS);
+
return vXResponse;
}
+
return vXResponse;
}
@@ -414,8 +474,10 @@ public VXResponse hasPermission(VXResource vXResource, int permission) {
*/
public boolean isAdmin() {
UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
+
if (currentUserSession == null) {
logger.debug("Unable to find session.");
+
return false;
}
@@ -424,10 +486,13 @@ public boolean isAdmin() {
public boolean isAuditAdmin() {
UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
+
if (currentUserSession == null) {
logger.debug("Unable to find session.");
+
return false;
}
+
return currentUserSession.isAuditUserAdmin();
}
@@ -437,8 +502,7 @@ public boolean isAuditAdmin() {
* @return
*/
public String getCurrentUserLoginId() {
- String ret = null;
-
+ String ret = null;
UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
if (currentUserSession != null) {
@@ -455,20 +519,26 @@ public String getCurrentUserLoginId() {
*/
public Long getXUserId() {
UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
+
if (currentUserSession == null) {
logger.debug("Unable to find session.");
+
return null;
}
XXPortalUser user = daoManager.getXXPortalUser().getById(currentUserSession.getUserId());
+
if (user == null) {
logger.debug("XXPortalUser not found with logged in user id : {}", currentUserSession.getUserId());
+
return null;
}
XXUser xUser = daoManager.getXXUser().findByUserName(user.getLoginId());
+
if (xUser == null) {
logger.debug("XXPortalUser not found for user id :{} with name {}", user.getId(), user.getFirstName());
+
return null;
}
@@ -478,6 +548,7 @@ public Long getXUserId() {
public void failUnauthenticatedIfNotAllowed() throws Exception {
if (UserGroupInformation.isSecurityEnabled()) {
UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
+
if (currentUserSession == null && !allowUnauthenticatedAccessInSecureEnvironment) {
throw new Exception("Unauthenticated access not allowed");
}
@@ -487,6 +558,7 @@ public void failUnauthenticatedIfNotAllowed() throws Exception {
public void failUnauthenticatedDownloadIfNotAllowed() throws Exception {
if (UserGroupInformation.isSecurityEnabled()) {
UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
+
if (currentUserSession == null && !allowUnauthenticatedDownloadAccessInSecureEnvironment) {
throw new Exception("Unauthenticated access not allowed");
}
@@ -510,8 +582,10 @@ public boolean matchHbasePolicy(String resourceName, List xResourceL
}
String[] splittedResources = stringUtil.split(resourceName, fileSeparator);
+
if (splittedResources.length < 1 || splittedResources.length > 3) {
logger.debug("Invalid resourceName name : {}", resourceName);
+
return false;
}
@@ -520,24 +594,24 @@ public boolean matchHbasePolicy(String resourceName, List xResourceL
String colName = splittedResources.length > 2 ? splittedResources[2] : StringUtil.WILDCARD_ASTERISK;
boolean policyMatched = false;
- // check all resources whether Hbase policy is enabled in any resource
- // of provided resource list
+
+ // check all resources whether Hbase policy is enabled in any resource of provided resource list
for (XXResource xResource : xResourceList) {
if (xResource.getResourceStatus() != AppConstants.STATUS_ENABLED) {
continue;
}
+
Long resourceId = xResource.getId();
boolean hasPermission = checkUsrPermForPolicy(xUserId, permission, resourceId);
- // if permission is enabled then load Tables,column family and
- // columns list from resource
+
+ // if permission is enabled then load Tables,column family and columns list from resource
if (!hasPermission) {
continue;
}
// 1. does the policy match the table?
- String[] xTables = stringUtil.isEmpty(xResource.getTables()) ? null : stringUtil.split(xResource.getTables(), ",");
-
- boolean matchFound = (xTables == null || xTables.length == 0) || matchPath(tblName, xTables);
+ String[] xTables = stringUtil.isEmpty(xResource.getTables()) ? null : stringUtil.split(xResource.getTables(), ",");
+ boolean matchFound = (xTables == null || xTables.length == 0) || matchPath(tblName, xTables);
if (matchFound) {
// 2. does the policy match the column?
@@ -558,6 +632,7 @@ public boolean matchHbasePolicy(String resourceName, List xResourceL
break;
}
}
+
return policyMatched;
}
@@ -583,8 +658,10 @@ public boolean matchHivePolicy(String resourceName, List xResourceLi
}
String[] splittedResources = stringUtil.split(resourceName, fileSeparator); // get list of resources
+
if (splittedResources.length < 1 || splittedResources.length > 3) {
logger.debug("Invalid resource name : {}", resourceName);
+
return false;
}
@@ -593,6 +670,7 @@ public boolean matchHivePolicy(String resourceName, List xResourceLi
String colName = splittedResources.length > 2 ? splittedResources[2] : StringUtil.WILDCARD_ASTERISK;
boolean policyMatched = false;
+
for (XXResource xResource : xResourceList) {
if (xResource.getResourceStatus() != RangerCommonEnums.STATUS_ENABLED) {
continue;
@@ -607,8 +685,7 @@ public boolean matchHivePolicy(String resourceName, List xResourceLi
// 1. does the policy match the database?
String[] xDatabases = stringUtil.isEmpty(xResource.getDatabases()) ? null : stringUtil.split(xResource.getDatabases(), ",");
-
- boolean matchFound = (xDatabases == null || xDatabases.length == 0) || matchPath(dbName, xDatabases);
+ boolean matchFound = (xDatabases == null || xDatabases.length == 0) || matchPath(dbName, xDatabases);
if (!matchFound) {
continue;
@@ -661,6 +738,7 @@ public boolean matchHivePolicy(String resourceName, List xResourceLi
}
}
}
+
return policyMatched;
}
@@ -677,12 +755,16 @@ public String replaceMetaChars(String path) {
if (path.contains("*")) {
String replacement = getRandomString(5, 60);
+
path = path.replaceAll("\\*", replacement);
}
+
if (path.contains("?")) {
String replacement = getRandomString(1, 1);
+
path = path.replaceAll("\\?", replacement);
}
+
return path;
}
@@ -705,6 +787,7 @@ public boolean isGroupInList(Long groupId, List xGroupList) {
return true;
}
}
+
return false;
}
@@ -721,17 +804,22 @@ public boolean isRecursiveWildCardMatch(String pathToCheck, String wildcardPath)
if (wildcardPath != null && wildcardPath.equals(fileSeparator)) {
return true;
}
+
StringBuilder sb = new StringBuilder();
+
for (String p : pathToCheck.split(fileSeparator)) {
sb.append(p);
+
boolean matchFound = FilenameUtils.wildcardMatch(sb.toString(), wildcardPath);
+
if (matchFound) {
return true;
}
+
sb.append(fileSeparator);
}
- sb = null;
}
+
return false;
}
@@ -749,6 +837,7 @@ public List getResorceTypeParentHirearchy(int resourceType, int assetTy
resourceTypeList.add(AppConstants.RESOURCE_PATH);
} else if (assetType == AppConstants.ASSET_HIVE) {
resourceTypeList.add(AppConstants.RESOURCE_DB);
+
if (resourceType == AppConstants.RESOURCE_TABLE) {
resourceTypeList.add(AppConstants.RESOURCE_TABLE);
} else if (resourceType == AppConstants.RESOURCE_UDF) {
@@ -759,6 +848,7 @@ public List getResorceTypeParentHirearchy(int resourceType, int assetTy
}
} else if (assetType == AppConstants.ASSET_HBASE) {
resourceTypeList.add(AppConstants.RESOURCE_TABLE);
+
if (resourceType == AppConstants.RESOURCE_COL_FAM) {
resourceTypeList.add(AppConstants.RESOURCE_COL_FAM);
} else if (resourceType == AppConstants.RESOURCE_COLUMN) {
@@ -780,12 +870,15 @@ public List getResorceTypeParentHirearchy(int resourceType, int assetTy
*/
public boolean comparePathsForExactMatch(String path1, String path2) {
String pathSeparator = fileSeparator;
+
if (!path1.endsWith(pathSeparator)) {
path1 = path1.concat(pathSeparator);
}
+
if (!path2.endsWith(pathSeparator)) {
path2 = path2.concat(pathSeparator);
}
+
return path1.equalsIgnoreCase(path2);
}
@@ -807,20 +900,24 @@ public boolean nonRecursiveWildCardMatch(String pathToCheck, String wildcardPath
if (pathToCheckArray.size() == wildcardPathArray.size()) {
boolean match = false;
+
for (int index = 0; index < pathToCheckArray.size(); index++) {
match = matchPath(pathToCheckArray.get(index), wildcardPathArray.get(index));
+
if (!match) {
return match;
}
}
+
return match;
}
}
+
return false;
}
public void createTrxLog(List trxLogList) {
- if (trxLogList == null || trxLogList.size() == 0) {
+ if (trxLogList == null || trxLogList.isEmpty()) {
return;
}
@@ -868,8 +965,10 @@ public void setAuditDBType(String auditDBType) {
*/
public boolean isKeyAdmin() {
UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
+
if (currentUserSession == null) {
logger.debug("Unable to find session.");
+
return false;
}
@@ -878,10 +977,12 @@ public boolean isKeyAdmin() {
public boolean isAuditKeyAdmin() {
UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
+
if (currentUserSession == null) {
logger.debug("Unable to find session.");
return false;
}
+
return (currentUserSession.isAuditKeyAdmin());
}
@@ -893,6 +994,7 @@ public boolean isAuditKeyAdmin() {
*/
public Boolean hasAccess(XXDBBase xxDbBase, RangerBaseModelObject baseModel) {
UserSessionBase session = ContextUtil.getCurrentUserSession();
+
if (session == null) {
logger.info("User session not found, granting access.");
return true;
@@ -904,17 +1006,18 @@ public Boolean hasAccess(XXDBBase xxDbBase, RangerBaseModelObject baseModel) {
boolean isAuditorKeyAdmin = session.isAuditKeyAdmin();
boolean isUser = session.getUserRoleList().contains(RangerConstants.ROLE_USER);
- if (xxDbBase != null && xxDbBase instanceof XXServiceDef) {
+ if (xxDbBase instanceof XXServiceDef) {
return hasAccessToXXServiceDef((XXServiceDef) xxDbBase, isKeyAdmin, isSysAdmin, isAuditor, isAuditorKeyAdmin, isUser);
}
- if (xxDbBase != null && xxDbBase instanceof XXService) {
+ if (xxDbBase instanceof XXService) {
return hasAccessToXXService((XXService) xxDbBase, isKeyAdmin, isSysAdmin, isAuditor, isAuditorKeyAdmin, isUser);
}
- if (baseModel != null && baseModel instanceof RangerServiceHeaderInfo) {
+ if (baseModel instanceof RangerServiceHeaderInfo) {
return hasAccessToRangerServiceHeaderInfo((RangerServiceHeaderInfo) baseModel, isKeyAdmin, isSysAdmin, isAuditor, isAuditorKeyAdmin, isUser);
}
+
return false;
}
@@ -932,6 +1035,7 @@ public void hasAdminPermissions(String objType) {
public void hasKMSPermissions(String objType, String implClassName) {
UserSessionBase session = ContextUtil.getCurrentUserSession();
+
if (session == null) {
throw restErrorUtil.createRESTException("UserSession cannot be null, only KeyAdmin can create/update/delete " + objType, MessageEnums.OPER_NO_PERMISSION);
}
@@ -951,24 +1055,34 @@ public void hasKMSPermissions(String objType, String implClassName) {
public boolean checkUserAccessible(VXUser vXUser) {
boolean isAccessible = true;
Collection roleList = userMgr.getRolesByLoginId(vXUser.getName());
+
if (isKeyAdmin()) {
- if (vXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN) || vXUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR) || roleList.contains(RangerConstants.ROLE_SYS_ADMIN) || roleList.contains(RangerConstants.ROLE_ADMIN_AUDITOR)) {
+ if (vXUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN)
+ || vXUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN_AUDITOR)
+ || roleList.contains(RangerConstants.ROLE_SYS_ADMIN)
+ || roleList.contains(RangerConstants.ROLE_ADMIN_AUDITOR)) {
isAccessible = false;
}
}
if (isAdmin()) {
- if (vXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN) || vXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR) || roleList.contains(RangerConstants.ROLE_KEY_ADMIN) || roleList.contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) {
+ if (vXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN)
+ || vXUser.getUserRoleList().contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)
+ || roleList.contains(RangerConstants.ROLE_KEY_ADMIN)
+ || roleList.contains(RangerConstants.ROLE_KEY_ADMIN_AUDITOR)) {
isAccessible = false;
}
}
+
if (!isAccessible) {
throw restErrorUtil.createRESTException("Logged in user is not allowed to create/update user", MessageEnums.OPER_NO_PERMISSION);
}
+
return isAccessible;
}
public boolean isSSOEnabled() {
UserSessionBase session = ContextUtil.getCurrentUserSession();
+
if (session != null) {
return session.isSSOEnabled() == null ? PropertiesUtil.getBooleanProperty("ranger.sso.enabled", false) : session.isSSOEnabled();
} else {
@@ -980,20 +1094,22 @@ public boolean isUserAllowed(RangerService rangerService, String cfgNameAllowedU
Map map = rangerService.getConfigs();
String user = null;
UserSessionBase userSession = ContextUtil.getCurrentUserSession();
+
if (userSession != null) {
user = userSession.getLoginId();
}
+
if (map != null && map.containsKey(cfgNameAllowedUsers)) {
String userNames = map.get(cfgNameAllowedUsers);
String[] userList = userNames.split(",");
- if (userList != null) {
- for (String u : userList) {
- if ("*".equals(u) || (u.equalsIgnoreCase(user))) {
- return true;
- }
+
+ for (String u : userList) {
+ if ("*".equals(u) || (u.equalsIgnoreCase(user))) {
+ return true;
}
}
}
+
return false;
}
@@ -1003,13 +1119,17 @@ public boolean isUserAllowedForGrantRevoke(RangerService rangerService, String u
public boolean isUserRangerAdmin(String username) {
boolean isAdmin = false;
+
try {
VXUser vxUser = xUserService.getXUserByUserName(username);
+
if (vxUser != null && (vxUser.getUserRoleList().contains(RangerConstants.ROLE_ADMIN) || vxUser.getUserRoleList().contains(RangerConstants.ROLE_SYS_ADMIN))) {
isAdmin = true;
}
} catch (Exception ex) {
+ // ignored
}
+
return isAdmin;
}
@@ -1029,14 +1149,14 @@ public boolean isUserInConfigParameter(RangerService rangerService, String confi
if (map != null && map.containsKey(configParamName)) {
String userNames = map.get(configParamName);
String[] userList = userNames.split(",");
- if (userList != null) {
- for (String u : userList) {
- if ("*".equals(u) || (u.equalsIgnoreCase(userName))) {
- return true;
- }
+
+ for (String u : userList) {
+ if ("*".equals(u) || (u.equalsIgnoreCase(userName))) {
+ return true;
}
}
}
+
return false;
}
@@ -1062,41 +1182,44 @@ public boolean isAnyGroupInConfigParameter(RangerService rangerService, String c
public void blockAuditorRoleUser() {
UserSessionBase session = ContextUtil.getCurrentUserSession();
+
if (session != null) {
if (session.isAuditKeyAdmin() || session.isAuditUserAdmin()) {
VXResponse vXResponse = new VXResponse();
+
vXResponse.setStatusCode(HttpServletResponse.SC_FORBIDDEN);
- vXResponse.setMsgDesc("Operation" + " denied. LoggedInUser=" + session.getXXPortalUser().getId() + " ,isn't permitted to perform the action.");
+ vXResponse.setMsgDesc("Operation denied. LoggedInUser=" + session.getXXPortalUser().getId() + " ,isn't permitted to perform the action.");
+
throw restErrorUtil.generateRESTException(vXResponse);
}
} else {
VXResponse vXResponse = new VXResponse();
+
vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null
vXResponse.setMsgDesc("Bad Credentials");
+
throw restErrorUtil.generateRESTException(vXResponse);
}
}
public boolean hasModuleAccess(String moduleName) {
UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
+
if (currentUserSession == null) {
return false;
}
+
if (!currentUserSession.isUserAdmin() && !currentUserSession.isAuditUserAdmin()) {
return currentUserSession.getRangerUserPermission().getUserPermissions().contains(moduleName);
}
+
return true;
}
public void removeEmptyStrings(List list) {
if (!CollectionUtils.isEmpty(list)) {
- Iterator i = list.iterator();
- while (i.hasNext()) {
- String item = i.next();
- if (item == null || StringUtils.isEmpty(StringUtils.trim(item))) {
- i.remove();
- }
- }
+ list.removeIf(StringUtils::isBlank);
+
trimAll(list);
}
}
@@ -1105,6 +1228,7 @@ public void trimAll(List list) {
if (!CollectionUtils.isEmpty(list)) {
for (int i = 0; i < list.size(); i++) {
String item = list.get(i);
+
if (item.startsWith(" ") || item.endsWith(" ")) {
list.set(i, StringUtils.trim(item));
}
@@ -1123,6 +1247,7 @@ public boolean getCreatePrincipalsIfAbsent() {
public void bulkModeOnlyFlushAndClear() {
if (BATCH_CLEAR_ENABLED) {
XXDBBaseDao xXDBBaseDao = daoManager.getXXDBBase();
+
if (xXDBBaseDao != null) {
xXDBBaseDao.flush();
xXDBBaseDao.clear();
@@ -1132,12 +1257,15 @@ public void bulkModeOnlyFlushAndClear() {
public boolean checkAdminAccess() {
UserSessionBase currentUserSession = ContextUtil.getCurrentUserSession();
+
if (currentUserSession != null) {
return currentUserSession.isUserAdmin();
} else {
VXResponse vXResponse = new VXResponse();
+
vXResponse.setStatusCode(HttpServletResponse.SC_UNAUTHORIZED); // user is null
vXResponse.setMsgDesc("Bad Credentials");
+
throw restErrorUtil.generateRESTException(vXResponse);
}
}
@@ -1161,18 +1289,24 @@ public boolean isGdsService(XXDBBase xxdbBase) {
*/
private boolean matchHdfsPolicy(String resourceName, List xResourceList, Long xUserId, int permission) {
boolean matchFound = false;
+
resourceName = replaceMetaChars(resourceName);
for (XXResource xResource : xResourceList) {
if (xResource.getResourceStatus() != RangerCommonEnums.STATUS_ENABLED) {
continue;
}
+
Long resourceId = xResource.getId();
+
matchFound = checkUsrPermForPolicy(xUserId, permission, resourceId);
+
if (matchFound) {
matchFound = false;
+
String resource = xResource.getName();
String[] dbResourceNameList = resource.split(",");
+
for (String dbResourceName : dbResourceNameList) {
if (comparePathsForExactMatch(resourceName, dbResourceName)) {
matchFound = true;
@@ -1183,15 +1317,18 @@ private boolean matchHdfsPolicy(String resourceName, List xResourceL
matchFound = nonRecursiveWildCardMatch(resourceName, dbResourceName);
}
}
+
if (matchFound) {
break;
}
}
+
if (matchFound) {
break;
}
}
}
+
return matchFound;
}
@@ -1208,22 +1345,25 @@ private boolean matchHdfsPolicy(String resourceName, List xResourceL
private boolean matchKnoxPolicy(String resourceName, List xResourceList, Long xUserId, int permission) {
String[] splittedResources = stringUtil.split(resourceName, fileSeparator);
int numberOfResources = splittedResources.length;
+
if (numberOfResources < 1 || numberOfResources > 3) {
logger.debug("Invalid policy name : {}", resourceName);
+
return false;
}
boolean policyMatched = false;
- // check all resources whether Knox policy is enabled in any resource
- // of provided resource list
+
+ // check all resources whether Knox policy is enabled in any resource of provided resource list
for (XXResource xResource : xResourceList) {
if (xResource.getResourceStatus() != RangerCommonEnums.STATUS_ENABLED) {
continue;
}
+
Long resourceId = xResource.getId();
boolean hasPermission = checkUsrPermForPolicy(xUserId, permission, resourceId);
- // if permission is enabled then load Topologies,services list from
- // resource
+
+ // if permission is enabled then load Topologies,services list from resource
if (hasPermission) {
String[] xTopologies = (xResource.getTopologies() == null || "".equalsIgnoreCase(xResource.getTopologies())) ? null : stringUtil.split(xResource.getTopologies(), ",");
String[] xServices = (xResource.getServices() == null || "".equalsIgnoreCase(xResource.getServices())) ? null : stringUtil.split(xResource.getServices(), ",");
@@ -1232,6 +1372,7 @@ private boolean matchKnoxPolicy(String resourceName, List xResourceL
for (int index = 0; index < numberOfResources; index++) {
matchFound = false;
+
// check whether given table resource matches with any
// existing topology resource
if (index == 0) {
@@ -1243,12 +1384,11 @@ private boolean matchKnoxPolicy(String resourceName, List xResourceL
}
}
}
+
if (!matchFound) {
break;
}
- } // check whether given service resource matches with
- // any existing service resource
- else if (index == 1) {
+ } else if (index == 1) { // check whether given service resource matches with any existing service resource
if (xServices != null) {
for (String xService : xServices) {
if (matchPath(splittedResources[index], xService)) {
@@ -1257,17 +1397,20 @@ else if (index == 1) {
}
}
}
+
if (!matchFound) {
break;
}
}
}
+
if (matchFound) {
policyMatched = true;
break;
}
}
}
+
return policyMatched;
}
@@ -1284,29 +1427,34 @@ else if (index == 1) {
private boolean matchStormPolicy(String resourceName, List xResourceList, Long xUserId, int permission) {
String[] splittedResources = stringUtil.split(resourceName, fileSeparator);
int numberOfResources = splittedResources.length;
+
if (numberOfResources < 1 || numberOfResources > 3) {
logger.debug("Invalid policy name : {}", resourceName);
+
return false;
}
boolean policyMatched = false;
+
// check all resources whether Knox policy is enabled in any resource
// of provided resource list
for (XXResource xResource : xResourceList) {
if (xResource.getResourceStatus() != RangerCommonEnums.STATUS_ENABLED) {
continue;
}
+
Long resourceId = xResource.getId();
boolean hasPermission = checkUsrPermForPolicy(xUserId, permission, resourceId);
+
// if permission is enabled then load Topologies,services list from
// resource
if (hasPermission) {
String[] xTopologies = (xResource.getTopologies() == null || "".equalsIgnoreCase(xResource.getTopologies())) ? null : stringUtil.split(xResource.getTopologies(), ",");
-
- boolean matchFound = false;
+ boolean matchFound = false;
for (int index = 0; index < numberOfResources; index++) {
matchFound = false;
+
// check whether given table resource matches with any
// existing topology resource
if (index == 0 && xTopologies != null) {
@@ -1319,12 +1467,14 @@ private boolean matchStormPolicy(String resourceName, List xResource
} // check whether given service resource matches with
// any existing service resource
}
+
if (matchFound) {
policyMatched = true;
break;
}
}
}
+
return policyMatched;
}
@@ -1338,10 +1488,13 @@ private boolean matchStormPolicy(String resourceName, List xResource
private String getRandomString(int minLen, int maxLen) {
StringBuilder sb = new StringBuilder();
int len = getRandomInt(minLen, maxLen);
+
for (int i = 0; i < len; i++) {
int charIdx = random.nextInt(PATH_CHAR_SET_LEN);
+
sb.append(PATH_CHAR_SET[charIdx]);
}
+
return sb.toString();
}
@@ -1358,9 +1511,11 @@ private int getRandomInt(int min, int max) {
} else {
int interval = max - min;
int randomNum = random.nextInt();
+
if (randomNum < 0) {
randomNum = Math.abs(randomNum);
}
+
return ((randomNum % interval) + min);
}
}
@@ -1380,6 +1535,7 @@ private boolean checkUsrPermForPolicy(Long xUserId, int permission, Long resourc
List permMapList = daoManager.getXXPermMap().findByResourceId(resourceId);
Long publicGroupId = getPublicGroupId();
boolean matchFound = false;
+
for (XXPermMap permMap : permMapList) {
if (permMap.getPermType() == permission) {
if (permMap.getPermFor() == AppConstants.XA_PERM_FOR_GROUP) {
@@ -1391,10 +1547,12 @@ private boolean checkUsrPermForPolicy(Long xUserId, int permission, Long resourc
matchFound = permMap.getUserId().equals(xUserId);
}
}
+
if (matchFound) {
break;
}
}
+
return matchFound;
}
@@ -1442,6 +1600,7 @@ private boolean matchPath(String pathToCheck, String[] wildCardPaths) {
private Boolean hasAccessToXXServiceDef(XXServiceDef xxDbBase, boolean isKeyAdmin, boolean isSysAdmin, boolean isAuditor, boolean isAuditorKeyAdmin, boolean isUser) {
XXServiceDef xServiceDef = xxDbBase;
final String implClass = xServiceDef.getImplclassname();
+
if (EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(implClass)) {
// KMS case
return isKeyAdmin || isAuditorKeyAdmin;
@@ -1461,6 +1620,7 @@ private Boolean hasAccessToXXService(XXService xxDbBase, boolean isKeyAdmin, boo
XXService xService = xxDbBase;
XXServiceDef xServiceDef = daoManager.getXXServiceDef().getById(xService.getType());
String implClass = xServiceDef.getImplclassname();
+
if (EmbeddedServiceDefsUtil.KMS_IMPL_CLASS_NAME.equals(implClass)) {
// KMS case
return isKeyAdmin || isAuditorKeyAdmin;
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminCache.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminCache.java
index 5b631766cd..3bd5fb5537 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminCache.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminCache.java
@@ -121,11 +121,10 @@ final RangerPolicyAdmin getServicePoliciesAdmin(String serviceName, ServiceStore
private RangerPolicyAdminWrapper addOrUpdatePolicyAdmin(RangerPolicyAdminWrapper policyAdminWrapper, ServicePolicies policies, RangerRoles roles, RangerPolicyEngineOptions options) {
final RangerPolicyAdminWrapper ret;
- RangerPolicyAdmin policyAdmin = null;
- boolean isPolicyEngineShared = false;
-
- RangerPolicyAdminImpl oldPolicyAdmin = policyAdminWrapper == null ? null : (RangerPolicyAdminImpl) policyAdminWrapper.getPolicyAdmin();
- Boolean hasPolicyDeltas = RangerPolicyDeltaUtil.hasPolicyDeltas(policies);
+ RangerPolicyAdmin policyAdmin = null;
+ boolean isPolicyEngineShared = false;
+ RangerPolicyAdminImpl oldPolicyAdmin = policyAdminWrapper == null ? null : (RangerPolicyAdminImpl) policyAdminWrapper.getPolicyAdmin();
+ Boolean hasPolicyDeltas = RangerPolicyDeltaUtil.hasPolicyDeltas(policies);
if (hasPolicyDeltas != null) {
if (hasPolicyDeltas.equals(Boolean.TRUE)) {
@@ -134,6 +133,7 @@ private RangerPolicyAdminWrapper addOrUpdatePolicyAdmin(RangerPolicyAdminWrapper
try {
policyAdminWrapper.getLock().lockInterruptibly();
+
isLocked = true;
} catch (Exception e) {
// Ignore
@@ -142,8 +142,10 @@ private RangerPolicyAdminWrapper addOrUpdatePolicyAdmin(RangerPolicyAdminWrapper
if (isLocked) {
try {
policyAdmin = RangerPolicyAdminImpl.getPolicyAdmin(oldPolicyAdmin, policies);
+
if (policyAdmin != null) {
policyAdmin.setRoles(roles);
+
isPolicyEngineShared = true;
}
} finally {
@@ -157,21 +159,28 @@ private RangerPolicyAdminWrapper addOrUpdatePolicyAdmin(RangerPolicyAdminWrapper
if (policies.getPolicies() == null) {
policies.setPolicies(new ArrayList<>());
}
+
policyAdmin = addPolicyAdmin(policies, roles, options);
}
} else {
LOG.warn("Provided policies do not require policy change !! [{}]. Keeping old policy-engine!", policies);
+
policyAdmin = oldPolicyAdmin;
}
if (policyAdmin != null) {
- if (oldPolicyAdmin == null) {
- LOG.debug("Adding policy-engine to cache with serviceName:[{}] as key", policies.getServiceName());
- } else {
- LOG.debug("Replacing policy-engine in cache with serviceName:[{}] as key", policies.getServiceName());
+ if (LOG.isDebugEnabled()) {
+ if (oldPolicyAdmin == null) {
+ LOG.debug("Adding policy-engine to cache with serviceName:[{}] as key", policies.getServiceName());
+ } else {
+ LOG.debug("Replacing policy-engine in cache with serviceName:[{}] as key", policies.getServiceName());
+ }
}
+
ret = new RangerPolicyAdminWrapper(policyAdmin);
+
policyAdminCache.put(policies.getServiceName(), ret);
+
if (oldPolicyAdmin != null && oldPolicyAdmin != policyAdmin) {
oldPolicyAdmin.releaseResources(!isPolicyEngineShared);
}
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminImpl.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminImpl.java
index 1e7a5f069d..95ed16dad5 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminImpl.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyAdminImpl.java
@@ -66,18 +66,19 @@ public class RangerPolicyAdminImpl implements RangerPolicyAdmin {
private static final Logger LOG = LoggerFactory.getLogger(RangerPolicyAdminImpl.class);
private static final Logger PERF_POLICYENGINE_REQUEST_LOG = RangerPerfTracer.getPerfLogger("policyengine.request");
- private static final Map wildcardEvalContext = new HashMap() {
+ private static final Map wildcardEvalContext = new HashMap() {
@Override
public Object get(Object key) {
return RangerAbstractResourceMatcher.WILDCARD_ASTERISK;
}
};
- private final PolicyEngine policyEngine;
- private final RangerAccessRequestProcessor requestProcessor;
- private ServiceDBStore serviceDBStore;
+
+ private final PolicyEngine policyEngine;
+ private final RangerAccessRequestProcessor requestProcessor;
+ private ServiceDBStore serviceDBStore;
RangerPolicyAdminImpl(ServicePolicies servicePolicies, RangerPluginContext pluginContext, RangerRoles roles) {
- this.policyEngine = new PolicyEngine(servicePolicies, pluginContext, roles, ServiceDBStore.supportsInPlacePolicyUpdates);
+ this.policyEngine = new PolicyEngine(servicePolicies, pluginContext, roles, ServiceDBStore.SUPPORTS_IN_PLACE_POLICY_UPDATES);
this.requestProcessor = new RangerDefaultRequestProcessor(policyEngine);
}
@@ -116,25 +117,30 @@ public boolean isDelegatedAdminAccessAllowed(RangerAccessResource resource, Stri
}
try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) {
- if (readLock.isLockingEnabled()) {
- LOG.debug("Acquired lock - {}", readLock);
+ if (LOG.isDebugEnabled()) {
+ if (readLock.isLockingEnabled()) {
+ LOG.debug("Acquired lock - {}", readLock);
+ }
}
final RangerPolicyRepository matchedRepository = policyEngine.getRepositoryForZone(zoneName);
if (matchedRepository != null) {
- Set roles = getRolesFromUserAndGroups(user, userGroups);
- Set requestedAccesses = new HashSet<>(accessTypes);
+ Set roles = getRolesFromUserAndGroups(user, userGroups);
+ Set requestedAccesses = new HashSet<>(accessTypes);
+ RangerAccessRequestImpl request = new RangerAccessRequestImpl();
- RangerAccessRequestImpl request = new RangerAccessRequestImpl();
request.setResource(resource);
for (RangerPolicyEvaluator evaluator : matchedRepository.getLikelyMatchPolicyEvaluators(request, RangerPolicy.POLICY_TYPE_ACCESS)) {
Set allowedAccesses = evaluator.getAllowedAccesses(resource, user, userGroups, roles, requestedAccesses);
+
if (CollectionUtils.isNotEmpty(allowedAccesses)) {
requestedAccesses.removeAll(allowedAccesses);
+
if (CollectionUtils.isEmpty(requestedAccesses)) {
LOG.debug("Access granted by policy:[{}]", evaluator.getPolicy());
+
ret = true;
break;
}
@@ -142,6 +148,7 @@ public boolean isDelegatedAdminAccessAllowed(RangerAccessResource resource, Stri
}
}
}
+
RangerPerfTracer.log(perf);
LOG.debug("<== RangerPolicyAdminImpl.isDelegatedAdminAccessAllowed({}, {}, {}, {}, {}): {}", resource, zoneName, user, userGroups, accessTypes, ret);
@@ -166,8 +173,10 @@ public List getExactMatchPolicies(RangerAccessResource resource, S
List ret = null;
try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) {
- if (readLock.isLockingEnabled()) {
- LOG.debug("Acquired lock - {}", readLock);
+ if (LOG.isDebugEnabled()) {
+ if (readLock.isLockingEnabled()) {
+ LOG.debug("Acquired lock - {}", readLock);
+ }
}
RangerPolicyRepository policyRepository = policyEngine.getRepositoryForZone(zoneName);
@@ -197,8 +206,10 @@ public List getExactMatchPolicies(RangerPolicy policy, Map ret = null;
try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) {
- if (readLock.isLockingEnabled()) {
- LOG.debug("Acquired lock - {}", readLock);
+ if (LOG.isDebugEnabled()) {
+ if (readLock.isLockingEnabled()) {
+ LOG.debug("Acquired lock - {}", readLock);
+ }
}
RangerPolicyRepository policyRepository = policyEngine.getRepositoryForMatchedZone(policy);
@@ -224,12 +235,16 @@ public List getExactMatchPolicies(RangerPolicy policy, Map getMatchingPolicies(RangerAccessResource resource) {
LOG.debug("==> RangerPolicyAdminImpl.getMatchingPolicies({})", resource);
+
List ret;
try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) {
- if (readLock.isLockingEnabled()) {
- LOG.debug("Acquired lock - {}", readLock);
+ if (LOG.isDebugEnabled()) {
+ if (readLock.isLockingEnabled()) {
+ LOG.debug("Acquired lock - {}", readLock);
+ }
}
+
ret = getMatchingPolicies(resource, RangerPolicyEngine.ANY_ACCESS);
}
@@ -243,32 +258,44 @@ public long getPolicyVersion() {
long ret;
try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) {
- if (readLock.isLockingEnabled()) {
- LOG.debug("Acquired lock - {}", readLock);
+ if (LOG.isDebugEnabled()) {
+ if (readLock.isLockingEnabled()) {
+ LOG.debug("Acquired lock - {}", readLock);
+ }
}
+
ret = policyEngine.getPolicyVersion();
}
+
return ret;
}
@Override
public long getRoleVersion() {
long ret;
+
try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) {
- if (readLock.isLockingEnabled()) {
- LOG.debug("Acquired lock - {}", readLock);
+ if (LOG.isDebugEnabled()) {
+ if (readLock.isLockingEnabled()) {
+ LOG.debug("Acquired lock - {}", readLock);
+ }
}
+
ret = policyEngine.getRoleVersion();
}
+
return ret;
}
@Override
public void setRoles(RangerRoles roles) {
try (RangerReadWriteLock.RangerLock writeLock = policyEngine.getWriteLock()) {
- if (writeLock.isLockingEnabled()) {
- LOG.debug("Acquired lock - {}", writeLock);
+ if (LOG.isDebugEnabled()) {
+ if (writeLock.isLockingEnabled()) {
+ LOG.debug("Acquired lock - {}", writeLock);
+ }
}
+
policyEngine.setRoles(roles);
}
}
@@ -278,35 +305,49 @@ public String getServiceName() {
String ret;
try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) {
- if (readLock.isLockingEnabled()) {
- LOG.debug("Acquired lock - {}", readLock);
+ if (LOG.isDebugEnabled()) {
+ if (readLock.isLockingEnabled()) {
+ LOG.debug("Acquired lock - {}", readLock);
+ }
}
+
ret = policyEngine.getServiceName();
}
+
return ret;
}
@Override
public RangerServiceDef getServiceDef() {
RangerServiceDef ret;
+
try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) {
- if (readLock.isLockingEnabled()) {
- LOG.debug("Acquired lock - {}", readLock);
+ if (LOG.isDebugEnabled()) {
+ if (readLock.isLockingEnabled()) {
+ LOG.debug("Acquired lock - {}", readLock);
+ }
}
+
ret = policyEngine.getServiceDef();
}
+
return ret;
}
@Override
public Set getRolesFromUserAndGroups(String user, Set groups) {
Set ret;
+
try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) {
- if (readLock.isLockingEnabled()) {
- LOG.debug("Acquired lock - {}", readLock);
+ if (LOG.isDebugEnabled()) {
+ if (readLock.isLockingEnabled()) {
+ LOG.debug("Acquired lock - {}", readLock);
+ }
}
+
ret = policyEngine.getPluginContext().getAuthContext().getRolesForUserAndGroups(user, groups);
}
+
return ret;
}
@@ -314,11 +355,13 @@ public Set getRolesFromUserAndGroups(String user, Set groups) {
public Collection getZoneNamesForResource(Map resource) {
LOG.debug("==> RangerPolicyAdminImpl.getSecurityZonesForResource({})", resource);
- Collection ret = null;
+ Collection ret;
try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) {
- if (readLock.isLockingEnabled()) {
- LOG.debug("Acquired lock - {}", readLock);
+ if (LOG.isDebugEnabled()) {
+ if (readLock.isLockingEnabled()) {
+ LOG.debug("Acquired lock - {}", readLock);
+ }
}
ret = policyEngine.getMatchedZonesForResourceAndChildren(resource);
@@ -332,12 +375,16 @@ public Collection getZoneNamesForResource(Map resource) {
@Override
public String getUniquelyMatchedZoneName(GrantRevokeRequest grantRevokeRequest) {
LOG.debug("==> RangerPolicyAdminImpl.getUniquelyMatchedZoneName({})", grantRevokeRequest);
+
String ret;
try (RangerReadWriteLock.RangerLock readLock = policyEngine.getReadLock()) {
- if (readLock.isLockingEnabled()) {
- LOG.debug("Acquired lock - {}", readLock);
+ if (LOG.isDebugEnabled()) {
+ if (readLock.isLockingEnabled()) {
+ LOG.debug("Acquired lock - {}", readLock);
+ }
}
+
ret = policyEngine.getUniquelyMatchedZoneName(grantRevokeRequest.getResource());
}
@@ -363,13 +410,14 @@ public boolean isAccessAllowedByUnzonedPolicies(Map getAllowedUnzonedPolicies(String user, Set use
// TODO: run through evaluator in tagPolicyRepository as well
for (RangerPolicyEvaluator evaluator : policyEngine.getPolicyRepository().getPolicyEvaluators()) {
- RangerPolicy policy = evaluator.getPolicy();
-
- boolean isAccessAllowed = isAccessAllowedByUnzonedPolicies(policy.getResources(), policy.getAdditionalResources(), user, userGroups, accessType);
+ RangerPolicy policy = evaluator.getPolicy();
+ boolean isAccessAllowed = isAccessAllowedByUnzonedPolicies(policy.getResources(), policy.getAdditionalResources(), user, userGroups, accessType);
if (isAccessAllowed) {
ret.add(policy);
}
}
- LOG.debug("<== RangerPolicyAdminImpl.getAllowedByUnzonedPolicies({}, {}, {}): policyCount={} ", user, userGroups, accessType, ret.size());
+ LOG.debug("<== RangerPolicyAdminImpl.getAllowedByUnzonedPolicies({}, {}, {}): policyCount={}", user, userGroups, accessType, ret.size());
return ret;
}
@@ -405,7 +452,7 @@ public void setServiceStore(ServiceStore svcStore) {
}
boolean isDelegatedAdminAccessAllowed(RangerPolicy policy, String user, Set userGroups, Set roles, boolean isRead, Map evalContext) {
- LOG.debug("==> RangerPolicyAdminImpl.isDelegatedAdminAccessAllowed({}, {}, {}, {}, {})", policy.getId(), user, userGroups, roles, isRead, evalContext);
+ LOG.debug("==> RangerPolicyAdminImpl.isDelegatedAdminAccessAllowed({}, {}, {}, {}, {}, {})", policy.getId(), user, userGroups, roles, isRead, evalContext);
boolean ret = false;
RangerPerfTracer perf = null;
@@ -415,8 +462,10 @@ boolean isDelegatedAdminAccessAllowed(RangerPolicy policy, String user, Set accessTypes = getAllAccessTypes(policy, getServiceDef());
+
ret = isDelegatedAdminAccessAllowedForPolicy(matchedRepository, policy, user, userGroups, roles, accessTypes, true, evalContext);
} else {
// Get old policy from policy-engine
RangerPolicy oldPolicy = null;
+
if (policy.getId() != null) {
try {
oldPolicy = serviceDBStore.getPolicy(policy.getId());
@@ -442,19 +493,24 @@ boolean isDelegatedAdminAccessAllowed(RangerPolicy policy, String user, Set modifiedAccessTypes = getAllModifiedAccessTypes(oldPolicy, policy, getServiceDef());
+
ret = isDelegatedAdminAccessAllowedForPolicy(matchedRepository, policy, user, userGroups, roles, modifiedAccessTypes, false, evalContext);
} else {
Set removedAccessTypes = getAllAccessTypes(oldPolicy, getServiceDef());
// Ensure that current policy-engine (without current policy) allows old-policy to be modified
final boolean isOldPolicyChangeAllowed = isDelegatedAdminAccessAllowedForPolicy(matchedRepository, oldPolicy, user, userGroups, roles, removedAccessTypes, false, evalContext);
+
if (isOldPolicyChangeAllowed) {
Set addedAccessTypes = getAllAccessTypes(policy, getServiceDef());
+
ret = isDelegatedAdminAccessAllowedForPolicy(matchedRepository, policy, user, userGroups, roles, addedAccessTypes, false, evalContext);
}
}
} else {
- LOG.warn("Cannot get unmodified policy with id:[{}]. Checking if this", policy.getId());
+ LOG.warn("Cannot get unmodified policy with id:[{}]. Checking if thi", policy.getId());
+
Set addedAccessTypes = getAllAccessTypes(policy, getServiceDef());
+
ret = isDelegatedAdminAccessAllowedForPolicy(matchedRepository, policy, user, userGroups, roles, addedAccessTypes, false, evalContext);
}
}
@@ -463,7 +519,7 @@ boolean isDelegatedAdminAccessAllowed(RangerPolicy policy, String user, Set userGroups, Set roles, Set accessTypes, boolean isRead, Map evalContext) {
- LOG.debug("==> RangerPolicyAdminImpl.isDelegatedAdminAccessAllowedForPolicy({}, {}, {}, {}, {}, {}, {})", policy.getId(), user, userGroups, roles, accessTypes, isRead, evalContext);
+ LOG.debug("==> RangerPolicyAdminImpl.isDelegatedAdminAccessAllowedForPolicy({}, {}, {}, {}, accessTypes{}, {}, {})", policy.getId(), user, userGroups, roles, accessTypes, isRead, evalContext);
boolean ret = false;
@@ -486,9 +542,7 @@ private boolean isDelegatedAdminAccessAllowedForPolicy(RangerPolicyRepository ma
Set allowedAccesses = getAllowedAccesses(matchedRepository, policy.getResources(), user, userGroups, roles, accessTypes, evalContext);
- if (CollectionUtils.isEmpty(allowedAccesses)) {
- ret = false;
- } else {
+ if (CollectionUtils.isNotEmpty(allowedAccesses)) {
ret = isRead ? CollectionUtils.containsAny(allowedAccesses, accessTypes) : allowedAccesses.containsAll(accessTypes);
}
@@ -523,7 +577,7 @@ private boolean isDelegatedAdminAccessAllowedForPolicy(RangerPolicyRepository ma
}
}
- LOG.debug("<== RangerPolicyAdminImpl.isDelegatedAdminAccessAllowedForPolicy({}, {}, {}, {}, {}, {}, {}) : {}", policy.getId(), user, userGroups, roles, accessTypes, isRead, evalContext, ret);
+ LOG.debug("<== RangerPolicyAdminImpl.isDelegatedAdminAccessAllowedForPolicy({}, {}, {}, {}, accessTypes{}, {}, {}): {}", policy.getId(), user, userGroups, roles, accessTypes, isRead, evalContext, ret);
return ret;
}
@@ -596,12 +650,14 @@ private void getMatchingPoliciesForZone(RangerAccessRequest request, String zone
if (useTagPoliciesFromDefaultZone) {
if (StringUtils.isNotEmpty(policyZoneName)) {
- LOG.debug("Tag policy [zone: {}] does not belong to default zone. Not evaluating this policy:[{}]", policyZoneName, evaluator.getPolicy());
+ LOG.debug("Tag policy [zone:{}] does not belong to default zone. Not evaluating this policy:[{}]", policyZoneName, evaluator.getPolicy());
+
continue;
}
} else {
if (!StringUtils.equals(zoneName, policyZoneName)) {
LOG.debug("Tag policy [zone:{}] does not belong to the zone:[{}] of the accessed resource. Not evaluating this policy:[{}]", policyZoneName, zoneName, evaluator.getPolicy());
+
continue;
}
}
@@ -609,7 +665,8 @@ private void getMatchingPoliciesForZone(RangerAccessRequest request, String zone
for (RangerPolicyResourceEvaluator resourceEvaluator : evaluator.getResourceEvaluators()) {
RangerPolicyResourceMatcher matcher = resourceEvaluator.getPolicyResourceMatcher();
- if (matcher != null && (request.isAccessTypeAny() ? matcher.isMatch(tagResource, RangerPolicyResourceMatcher.MatchScope.ANY, null) : matcher.isMatch(tagResource, null))) {
+ if (matcher != null &&
+ (request.isAccessTypeAny() ? matcher.isMatch(tagResource, RangerPolicyResourceMatcher.MatchScope.ANY, null) : matcher.isMatch(tagResource, null))) {
ret.add(evaluator.getPolicy());
break;
@@ -627,7 +684,8 @@ private void getMatchingPoliciesForZone(RangerAccessRequest request, String zone
for (RangerPolicyResourceEvaluator resourceEvaluator : evaluator.getResourceEvaluators()) {
RangerPolicyResourceMatcher matcher = resourceEvaluator.getPolicyResourceMatcher();
- if (matcher != null && (request.isAccessTypeAny() ? matcher.isMatch(request.getResource(), RangerPolicyResourceMatcher.MatchScope.ANY, null) : matcher.isMatch(request.getResource(), null))) {
+ if (matcher != null &&
+ (request.isAccessTypeAny() ? matcher.isMatch(request.getResource(), RangerPolicyResourceMatcher.MatchScope.ANY, null) : matcher.isMatch(request.getResource(), null))) {
ret.add(evaluator.getPolicy());
break;
@@ -661,10 +719,12 @@ private Map getPolicyResourcesWithMacrosReplaced(M
for (String value : values) {
// RANGER-3082 - replace macros in value with ASTERISK
String modifiedValue = tokenReplacer.replaceTokens(value, evalContext);
+
modifiedValues.add(modifiedValue);
}
RangerPolicyResource modifiedPolicyResource = new RangerPolicyResource(modifiedValues, resourceValues.getIsExcludes(), resourceValues.getIsRecursive());
+
ret.put(resourceName, modifiedPolicyResource);
} else {
ret.put(resourceName, resourceValues);
@@ -689,7 +749,7 @@ private Set getAllAccessTypes(RangerPolicy policy, RangerServiceDef serv
Map> expandedAccesses = ServiceDefUtil.getExpandedImpliedGrants(serviceDef);
if (MapUtils.isNotEmpty(expandedAccesses)) {
- Integer policyType = policy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : policy.getPolicyType();
+ int policyType = policy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : policy.getPolicyType();
if (policyType == RangerPolicy.POLICY_TYPE_ACCESS) {
for (RangerPolicy.RangerPolicyItem item : policy.getPolicyItems()) {
@@ -697,16 +757,19 @@ private Set getAllAccessTypes(RangerPolicy policy, RangerServiceDef serv
ret.addAll(expandedAccesses.get(access.getType()));
}
}
+
for (RangerPolicy.RangerPolicyItem item : policy.getDenyPolicyItems()) {
for (RangerPolicy.RangerPolicyItemAccess access : item.getAccesses()) {
ret.addAll(expandedAccesses.get(access.getType()));
}
}
+
for (RangerPolicy.RangerPolicyItem item : policy.getAllowExceptions()) {
for (RangerPolicy.RangerPolicyItemAccess access : item.getAccesses()) {
ret.addAll(expandedAccesses.get(access.getType()));
}
}
+
for (RangerPolicy.RangerPolicyItem item : policy.getDenyExceptions()) {
for (RangerPolicy.RangerPolicyItemAccess access : item.getAccesses()) {
ret.addAll(expandedAccesses.get(access.getType()));
@@ -726,12 +789,15 @@ private Set getAllAccessTypes(RangerPolicy policy, RangerServiceDef serv
}
} else {
LOG.error("Unknown policy-type :[{}], returning empty access-type set", policyType);
+
isValid = false;
}
+
if (isValid && ret.isEmpty()) {
ret.add(RangerPolicyEngine.ADMIN_ACCESS);
}
}
+
return ret;
}
@@ -756,6 +822,7 @@ private Set getAllModifiedAccessTypes(RangerPolicy oldPolicy, RangerPoli
if (ret.isEmpty()) {
ret.add(RangerPolicyEngine.ADMIN_ACCESS);
}
+
return ret;
}
@@ -763,7 +830,7 @@ private void collectAccessTypes(RangerPolicy policy, RangerServiceDef serviceDef
Map> expandedAccesses = ServiceDefUtil.getExpandedImpliedGrants(serviceDef);
if (MapUtils.isNotEmpty(expandedAccesses)) {
- Integer policyType = policy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : policy.getPolicyType();
+ int policyType = policy.getPolicyType() == null ? RangerPolicy.POLICY_TYPE_ACCESS : policy.getPolicyType();
if (policyType == RangerPolicy.POLICY_TYPE_ACCESS) {
collectAccessTypes(expandedAccesses, policy.getPolicyItems(), userAccesses, groupAccesses, roleAccesses);
@@ -790,6 +857,7 @@ private void collectAccessTypes(Map> expandedAccesses
for (String user : item.getUsers()) {
Set oldAccesses = userAccesses.get(user);
+
if (oldAccesses != null) {
oldAccesses.addAll(accessTypes);
} else {
@@ -799,6 +867,7 @@ private void collectAccessTypes(Map> expandedAccesses
for (String group : item.getGroups()) {
Set oldAccesses = groupAccesses.get(group);
+
if (oldAccesses != null) {
oldAccesses.addAll(accessTypes);
} else {
@@ -808,6 +877,7 @@ private void collectAccessTypes(Map> expandedAccesses
for (String role : item.getRoles()) {
Set oldAccesses = roleAccesses.get(role);
+
if (oldAccesses != null) {
oldAccesses.addAll(accessTypes);
} else {
@@ -822,17 +892,22 @@ private Set getAccessTypesDiff(Map> newAccessesMap,
for (Map.Entry> entry : newAccessesMap.entrySet()) {
Set oldAccesses = oldAccessesMap.get(entry.getKey());
+
if (oldAccesses != null) {
Collection added = CollectionUtils.subtract(entry.getValue(), oldAccesses);
+
ret.addAll(added);
} else {
ret.addAll(entry.getValue());
}
}
+
for (Map.Entry> entry : oldAccessesMap.entrySet()) {
Set newAccesses = newAccessesMap.get(entry.getKey());
+
if (newAccesses != null) {
Collection removed = CollectionUtils.subtract(entry.getValue(), newAccesses);
+
ret.addAll(removed);
} else {
ret.addAll(entry.getValue());
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyRetriever.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyRetriever.java
index 1a6a99d704..f43b982188 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyRetriever.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerPolicyRetriever.java
@@ -43,8 +43,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.PlatformTransactionManager;
-import org.springframework.transaction.TransactionStatus;
-import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.ArrayList;
@@ -57,15 +55,15 @@ public class RangerPolicyRetriever {
static final Logger LOG = LoggerFactory.getLogger(RangerPolicyRetriever.class);
static final Logger PERF_LOG = RangerPerfTracer.getPerfLogger("db.RangerPolicyRetriever");
- private final RangerDaoManager daoMgr;
- private final LookupCache lookupCache = new LookupCache();
-
+ private final RangerDaoManager daoMgr;
+ private final LookupCache lookupCache = new LookupCache();
private final PlatformTransactionManager txManager;
private final TransactionTemplate txTemplate;
public RangerPolicyRetriever(RangerDaoManager daoMgr, PlatformTransactionManager txManager) {
this.daoMgr = daoMgr;
this.txManager = txManager;
+
if (this.txManager != null) {
this.txTemplate = new TransactionTemplate(this.txManager);
this.txTemplate.setReadOnly(true);
@@ -138,16 +136,21 @@ public List getServicePolicies(final XXService xService) {
if (xService != null) {
if (txTemplate == null) {
LOG.debug("Transaction Manager is null; Retrieving policies in the existing transaction");
+
RetrieverContext ctx = new RetrieverContext(xService);
+
ret = ctx.getAllPolicies();
} else {
LOG.debug("Retrieving policies in a new, read-only transaction");
PolicyLoaderThread t = new PolicyLoaderThread(txTemplate, xService);
+
t.setDaemon(true);
t.start();
+
try {
t.join();
+
ret = t.getPolicies();
} catch (InterruptedException ie) {
LOG.error("Failed to retrieve policies in a new, read-only thread.", ie);
@@ -159,7 +162,7 @@ public List getServicePolicies(final XXService xService) {
RangerPerfTracer.log(perf);
- LOG.debug("<== RangerPolicyRetriever.getServicePolicies(serviceName={}, serviceId={}): policyCount={}", serviceName, serviceId, (ret == null ? 0 : ret.size()));
+ LOG.debug("<== RangerPolicyRetriever.getServicePolicies(serviceName={}, serviceId={}): policyCount={}", serviceName, serviceId, ret == null ? 0 : ret.size());
return ret;
}
@@ -218,7 +221,7 @@ public RangerPolicy getPolicy(XXPolicy xPolicy, XXService xService) {
RangerPerfTracer.log(perf);
- LOG.debug("<== RangerPolicyRetriever.getPolicy({}): ", policyId, ret);
+ LOG.debug("<== RangerPolicyRetriever.getPolicy({}): {}", policyId, ret);
return ret;
}
@@ -268,7 +271,7 @@ public PolicyTextNameMap(Long policyId, String oldName, String currentName) {
private class PolicyLoaderThread extends Thread {
final TransactionTemplate txTemplate;
final XXService xService;
- List policies;
+ List policies;
PolicyLoaderThread(TransactionTemplate txTemplate, final XXService xService) {
this.txTemplate = txTemplate;
@@ -283,17 +286,17 @@ public List getPolicies() {
public void run() {
try {
txTemplate.setReadOnly(true);
- policies = txTemplate.execute(new TransactionCallback>() {
- @Override
- public List doInTransaction(TransactionStatus status) {
- try {
- RetrieverContext ctx = new RetrieverContext(xService);
- return ctx.getAllPolicies();
- } catch (Exception ex) {
- LOG.error("RangerPolicyRetriever.getServicePolicies(): Failed to get policies service:[{}] in a new transaction", xService.getName(), ex);
- status.setRollbackOnly();
- return null;
- }
+ policies = txTemplate.execute(status -> {
+ try {
+ RetrieverContext ctx = new RetrieverContext(xService);
+
+ return ctx.getAllPolicies();
+ } catch (Exception ex) {
+ LOG.error("RangerPolicyRetriever.getServicePolicies(): Failed to get policies for service:[{}] in a new transaction", xService.getName(), ex);
+
+ status.setRollbackOnly();
+
+ return null;
}
});
} catch (Throwable ex) {
@@ -303,8 +306,8 @@ public List doInTransaction(TransactionStatus status) {
}
class LookupCache {
- final Map userScreenNames = new HashMap();
- final Map zoneNames = new HashMap();
+ final Map userScreenNames = new HashMap<>();
+ final Map zoneNames = new HashMap<>();
final Map> roleMappingsPerPolicy = new HashMap<>();
final Map> groupMappingsPerPolicy = new HashMap<>();
final Map> userMappingsPerPolicy = new HashMap<>();
@@ -312,7 +315,7 @@ class LookupCache {
final Map> resourceMappingsPerPolicy = new HashMap<>();
final Map> dataMaskMappingsPerPolicy = new HashMap<>();
final Map> conditionMappingsPerPolicy = new HashMap<>();
- final Map policyLabels = new HashMap();
+ final Map policyLabels = new HashMap<>();
public void setResourceNameMapping(List resourceNameMapping) {
setNameMapping(resourceMappingsPerPolicy, resourceNameMapping);
@@ -410,13 +413,7 @@ void setNameMapping(Map> nameMappingContainer, List policyNameMap = nameMappingContainer.get(nameMapping.policyId);
-
- if (policyNameMap == null) {
- policyNameMap = new HashMap<>();
-
- nameMappingContainer.put(nameMapping.policyId, policyNameMap);
- }
+ Map policyNameMap = nameMappingContainer.computeIfAbsent(nameMapping.policyId, k -> new HashMap<>());
policyNameMap.put(nameMapping.oldName, nameMapping.currentName);
}
@@ -650,14 +647,18 @@ List getAllPolicies() {
private void getPolicyLabels(RangerPolicy ret) {
List xPolicyLabels = new ArrayList<>();
+
if (iterPolicyLabels != null) {
while (iterPolicyLabels.hasNext()) {
XXPolicyLabelMap xPolicyLabel = iterPolicyLabels.next();
+
if (xPolicyLabel.getPolicyId().equals(ret.getId())) {
String policyLabel = lookupCache.getPolicyLabelName(xPolicyLabel.getPolicyLabelId());
+
if (policyLabel != null) {
xPolicyLabels.add(policyLabel);
}
+
ret.setPolicyLabels(xPolicyLabels);
} else {
if (iterPolicyLabels.hasPrevious()) {
diff --git a/security-admin/src/main/java/org/apache/ranger/biz/RangerTagDBRetriever.java b/security-admin/src/main/java/org/apache/ranger/biz/RangerTagDBRetriever.java
index ee8c9010d9..779638e7bf 100644
--- a/security-admin/src/main/java/org/apache/ranger/biz/RangerTagDBRetriever.java
+++ b/security-admin/src/main/java/org/apache/ranger/biz/RangerTagDBRetriever.java
@@ -40,8 +40,6 @@
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.PlatformTransactionManager;
-import org.springframework.transaction.TransactionStatus;
-import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;
import java.util.ArrayList;
@@ -51,11 +49,13 @@
import java.util.Map;
public class RangerTagDBRetriever {
- public static final TypeReference subsumedDataType = new TypeReference>() {};
private static final Logger LOG = LoggerFactory.getLogger(RangerTagDBRetriever.class);
private static final Logger PERF_LOG = RangerPerfTracer.getPerfLogger("db.RangerTagDBRetriever");
- private final RangerDaoManager daoMgr;
- private final LookupCache lookupCache;
+
+ public static final TypeReference> subsumedDataType = new TypeReference>() {};
+
+ private final RangerDaoManager daoMgr;
+ private final LookupCache lookupCache;
private List serviceResources;
private Map tagDefs;
@@ -67,10 +67,12 @@ public class RangerTagDBRetriever {
if (txManager != null) {
txTemplate = new TransactionTemplate(txManager);
+
txTemplate.setReadOnly(true);
} else {
txTemplate = null;
}
+
this.lookupCache = new LookupCache();
if (this.daoMgr != null && xService != null) {
@@ -82,6 +84,7 @@ public class RangerTagDBRetriever {
if (txTemplate == null) {
LOG.debug("Load Tags in the same thread and using an existing transaction");
+
if (!initializeTagCache(xService)) {
LOG.error("Failed to get tags for service:[{}] in the same thread and using an existing transaction", xService.getName());
}
@@ -89,8 +92,10 @@ public class RangerTagDBRetriever {
LOG.debug("Load Tags in a separate thread and using a new transaction");
TagLoaderThread t = new TagLoaderThread(txTemplate, xService);
+
t.setDaemon(true);
t.start();
+
try {
t.join();
} catch (InterruptedException ie) {
@@ -116,6 +121,7 @@ Map getTags() {
if (CollectionUtils.isNotEmpty(serviceResources)) {
for (RangerServiceResource serviceResource : serviceResources) {
List tags = lookupCache.serviceResourceToTags.get(serviceResource.getId());
+
if (CollectionUtils.isNotEmpty(tags)) {
for (RangerTag tag : tags) {
ret.put(tag.getId(), tag);
@@ -133,15 +139,19 @@ Map> getResourceToTagIds() {
if (CollectionUtils.isNotEmpty(serviceResources)) {
for (RangerServiceResource serviceResource : serviceResources) {
List tags = lookupCache.serviceResourceToTags.get(serviceResource.getId());
+
if (CollectionUtils.isNotEmpty(tags)) {
List tagIds = new ArrayList<>();
+
ret.put(serviceResource.getId(), tagIds);
+
for (RangerTag tag : tags) {
tagIds.add(tag.getId());
}
}
}
}
+
return ret;
}
@@ -154,10 +164,12 @@ private boolean initializeTagCache(XXService xService) {
ret = true;
} catch (Exception ex) {
LOG.error("Failed to get tags for service:[{}]", xService.getName(), ex);
+
serviceResources = null;
tagDefs = null;
ret = false;
}
+
return ret;
}
@@ -213,17 +225,18 @@ private class TagLoaderThread extends Thread {
public void run() {
try {
txTemplate.setReadOnly(true);
- Boolean result = txTemplate.execute(new TransactionCallback() {
- @Override
- public Boolean doInTransaction(TransactionStatus status) {
- boolean ret = initializeTagCache(xService);
- if (!ret) {
- status.setRollbackOnly();
- LOG.error("Failed to get tags for service:[{}] in a new transaction", xService.getName());
- }
- return ret;
+ Boolean result = txTemplate.execute(status -> {
+ boolean ret = initializeTagCache(xService);
+
+ if (!ret) {
+ status.setRollbackOnly();
+
+ LOG.error("Failed to get tags for service:[{}] in a new transaction", xService.getName());
}
+
+ return ret;
});
+
LOG.debug("transaction result:[{}]", result);
} catch (Throwable ex) {
LOG.error("Failed to get tags for service:[{}] in a new transaction", xService.getName(), ex);
@@ -237,6 +250,7 @@ private class TagRetrieverServiceResourceContext {
TagRetrieverServiceResourceContext(XXService xService) {
Long serviceId = xService == null ? null : xService.getId();
+
this.service = xService;
List