use of org.apache.ranger.security.context.RangerAdminOpContext in project ranger by apache.
the class RangerBizUtil method setBulkMode.
public static boolean setBulkMode(boolean val) {
if (RangerContextHolder.getOpContext() != null) {
RangerContextHolder.getOpContext().setBulkModeContext(val);
} else {
RangerAdminOpContext opContext = new RangerAdminOpContext();
opContext.setBulkModeContext(val);
RangerContextHolder.setOpContext(opContext);
}
return isBulkMode();
}
use of org.apache.ranger.security.context.RangerAdminOpContext in project ranger by apache.
the class ContextUtil method isBulkModeContext.
public static boolean isBulkModeContext() {
RangerAdminOpContext context = RangerContextHolder.getOpContext();
boolean bulkMode = false;
if (context != null) {
bulkMode = context.isBulkModeContext();
}
return bulkMode;
}
use of org.apache.ranger.security.context.RangerAdminOpContext in project ranger by apache.
the class ServiceREST method importPoliciesFromFile.
@POST
@Path("/policies/importPoliciesFromFile")
@Consumes({ MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_JSON })
@Produces({ "application/json", "application/xml" })
@PreAuthorize("@rangerPreAuthSecurityHandler.isAdminOrKeyAdminRole()")
public void importPoliciesFromFile(@Context HttpServletRequest request, @FormDataParam("servicesMapJson") InputStream serviceMapStream, @FormDataParam("zoneMapJson") InputStream zoneMapStream, @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail, @QueryParam("isOverride") Boolean isOverride, @QueryParam("importType") String importType) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.importPoliciesFromFile()");
}
RangerAdminOpContext opContext = new RangerAdminOpContext();
opContext.setBulkModeContext(true);
RangerContextHolder.setOpContext(opContext);
RangerPerfTracer perf = null;
String metaDataInfo = null;
List<XXTrxLog> trxLogListError = new ArrayList<XXTrxLog>();
XXTrxLog xxTrxLogError = new XXTrxLog();
request.setAttribute(PARAM_IMPORT_IN_PROGRESS, true);
try {
if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.importPoliciesFromFile()");
}
List<XXTrxLog> trxLogList = new ArrayList<XXTrxLog>();
XXTrxLog xxTrxLog = new XXTrxLog();
xxTrxLog.setAction("IMPORT START");
xxTrxLog.setObjectClassType(AppConstants.CLASS_TYPE_RANGER_POLICY);
xxTrxLog.setPreviousValue("IMPORT START");
trxLogList.add(xxTrxLog);
bizUtil.createTrxLog(trxLogList);
if (isOverride == null) {
isOverride = false;
}
List<String> serviceNameList = new ArrayList<String>();
getServiceNameList(request, serviceNameList);
Map<String, String> servicesMappingMap = new LinkedHashMap<String, String>();
List<String> sourceServices = new ArrayList<String>();
List<String> destinationServices = new ArrayList<String>();
Map<String, String> zoneMappingMap = new LinkedHashMap<String, String>();
List<String> sourceZones = new ArrayList<String>();
List<String> destinationZones = new ArrayList<String>();
if (zoneMapStream != null) {
zoneMappingMap = svcStore.getMapFromInputStream(zoneMapStream);
processZoneMapping(zoneMappingMap, sourceZones, destinationZones);
}
if (serviceMapStream != null) {
servicesMappingMap = svcStore.getMapFromInputStream(serviceMapStream);
processServiceMapping(servicesMappingMap, sourceServices, destinationServices);
}
String fileName = fileDetail.getFileName();
int totalPolicyCreate = 0;
String zoneNameInJson = null;
Map<String, RangerPolicy> policiesMap = new LinkedHashMap<String, RangerPolicy>();
List<String> dataFileSourceServices = new ArrayList<String>();
if (fileName.endsWith("json")) {
try {
RangerExportPolicyList rangerExportPolicyList = null;
List<RangerPolicy> policies = null;
rangerExportPolicyList = processPolicyInputJsonForMetaData(uploadedInputStream, rangerExportPolicyList);
if (rangerExportPolicyList != null && !CollectionUtils.sizeIsEmpty(rangerExportPolicyList.getMetaDataInfo())) {
metaDataInfo = JsonUtilsV2.mapToJson(rangerExportPolicyList.getMetaDataInfo());
} else {
LOG.info("metadata info is not provided!!");
}
policies = getPoliciesFromProvidedJson(rangerExportPolicyList);
int i = 0;
if (CollectionUtils.sizeIsEmpty(servicesMappingMap) && isOverride) {
if (policies != null && !CollectionUtils.sizeIsEmpty(policies)) {
for (RangerPolicy policyInJson : policies) {
if (policyInJson != null) {
if (i == 0 && StringUtils.isNotBlank(policyInJson.getZoneName())) {
zoneNameInJson = policyInJson.getZoneName().trim();
}
if (StringUtils.isNotEmpty(policyInJson.getService().trim())) {
String serviceName = policyInJson.getService().trim();
if (CollectionUtils.isNotEmpty(serviceNameList) && serviceNameList.contains(serviceName) && !sourceServices.contains(serviceName) && !destinationServices.contains(serviceName)) {
sourceServices.add(serviceName);
destinationServices.add(serviceName);
} else if (CollectionUtils.isEmpty(serviceNameList) && !sourceServices.contains(serviceName) && !destinationServices.contains(serviceName)) {
sourceServices.add(serviceName);
destinationServices.add(serviceName);
}
} else {
LOG.error("Service Name or Policy Name is not provided!!");
throw restErrorUtil.createRESTException("Service Name or Policy Name is not provided!!");
}
}
i++;
}
}
} else if (!CollectionUtils.sizeIsEmpty(servicesMappingMap)) {
if (policies != null && !CollectionUtils.sizeIsEmpty(policies)) {
i = 0;
for (RangerPolicy policyInJson : policies) {
if (policyInJson != null) {
if (i == 0 && StringUtils.isNotBlank(policyInJson.getZoneName())) {
zoneNameInJson = policyInJson.getZoneName().trim();
}
if (StringUtils.isNotEmpty(policyInJson.getService().trim())) {
dataFileSourceServices.add(policyInJson.getService().trim());
} else {
LOG.error("Service Name or Policy Name is not provided!!");
throw restErrorUtil.createRESTException("Service Name or Policy Name is not provided!!");
}
i++;
}
}
if (!dataFileSourceServices.containsAll(sourceServices)) {
LOG.error("Json File does not contain sepcified source service name.");
throw restErrorUtil.createRESTException("Json File does not contain sepcified source service name.");
}
}
}
boolean deleteIfExists = ("true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_DELETE_IF_EXISTS)))) ? true : false;
boolean updateIfExists = ("true".equalsIgnoreCase(StringUtils.trimToEmpty(request.getParameter(PARAM_UPDATE_IF_EXISTS)))) ? true : false;
String polResource = request.getParameter(SearchFilter.POL_RESOURCE);
if (updateIfExists) {
isOverride = false;
}
String destinationZoneName = getDestinationZoneName(destinationZones, zoneNameInJson);
if (isOverride && !updateIfExists && StringUtils.isEmpty(polResource)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Deleting Policy from provided services in servicesMapJson file...");
}
if (CollectionUtils.isNotEmpty(sourceServices) && CollectionUtils.isNotEmpty(destinationServices)) {
// In order to delete Zone specific policies from service
deletePoliciesProvidedInServiceMap(sourceServices, destinationServices, destinationZoneName);
}
} else if (updateIfExists && StringUtils.isNotEmpty(polResource)) {
if (LOG.isDebugEnabled()) {
LOG.debug("Deleting Policy from provided services in servicesMapJson file for specific resource...");
}
if (CollectionUtils.isNotEmpty(sourceServices) && CollectionUtils.isNotEmpty(destinationServices)) {
// In order to delete Zone specific policies from service
deletePoliciesForResource(sourceServices, destinationServices, request, policies, destinationZoneName);
}
}
if (policies != null && !CollectionUtils.sizeIsEmpty(policies)) {
for (RangerPolicy policyInJson : policies) {
if (policyInJson != null) {
if (StringUtils.isNotBlank(destinationZoneName)) {
boolean isZoneServiceExistAtDestination = validateDestZoneServiceMapping(destinationZoneName, policyInJson, servicesMappingMap);
if (!isZoneServiceExistAtDestination) {
LOG.warn("provided service of policy in File is not associated with zone");
continue;
}
}
policiesMap = svcStore.createPolicyMap(zoneMappingMap, sourceZones, destinationZoneName, servicesMappingMap, sourceServices, destinationServices, policyInJson, // zone Info is also sent for creating policy map
policiesMap);
}
}
if (deleteIfExists) {
// deleting target policies if already exist
deleteExactMatchPolicyForResource(policies, request.getRemoteUser(), destinationZoneName);
}
}
totalPolicyCreate = createPolicesBasedOnPolicyMap(request, policiesMap, serviceNameList, updateIfExists, totalPolicyCreate);
if (!(totalPolicyCreate > 0)) {
LOG.error("zero policy is created from provided data file!!");
throw restErrorUtil.createRESTException("zero policy is created from provided data file!!");
}
} catch (IOException e) {
LOG.error(e.getMessage());
throw restErrorUtil.createRESTException(e.getMessage());
}
} else {
LOG.error("Provided file format is not supported!!");
throw restErrorUtil.createRESTException("Provided file format is not supported!!");
}
} catch (JsonSyntaxException ex) {
LOG.error("Provided json file is not valid!!", ex);
xxTrxLogError.setAction("IMPORT ERROR");
xxTrxLogError.setObjectClassType(AppConstants.CLASS_TYPE_RANGER_POLICY);
if (StringUtils.isNotEmpty(metaDataInfo)) {
xxTrxLogError.setPreviousValue(metaDataInfo);
}
trxLogListError.add(xxTrxLogError);
bizUtil.createTrxLog(trxLogListError);
throw restErrorUtil.createRESTException(ex.getMessage());
} catch (WebApplicationException excp) {
LOG.error("Error while importing policy from file!!", excp);
xxTrxLogError.setAction("IMPORT ERROR");
xxTrxLogError.setObjectClassType(AppConstants.CLASS_TYPE_RANGER_POLICY);
if (StringUtils.isNotEmpty(metaDataInfo)) {
xxTrxLogError.setPreviousValue(metaDataInfo);
}
trxLogListError.add(xxTrxLogError);
bizUtil.createTrxLog(trxLogListError);
throw excp;
} catch (Throwable excp) {
LOG.error("Error while importing policy from file!!", excp);
xxTrxLogError.setAction("IMPORT ERROR");
xxTrxLogError.setObjectClassType(AppConstants.CLASS_TYPE_RANGER_POLICY);
if (StringUtils.isNotEmpty(metaDataInfo)) {
xxTrxLogError.setPreviousValue(metaDataInfo);
}
trxLogListError.add(xxTrxLogError);
bizUtil.createTrxLog(trxLogListError);
throw restErrorUtil.createRESTException(excp.getMessage());
} finally {
RangerPerfTracer.log(perf);
List<XXTrxLog> trxLogListEnd = new ArrayList<XXTrxLog>();
XXTrxLog xxTrxLogEnd = new XXTrxLog();
xxTrxLogEnd.setAction("IMPORT END");
xxTrxLogEnd.setObjectClassType(AppConstants.CLASS_TYPE_RANGER_POLICY);
if (StringUtils.isNotEmpty(metaDataInfo)) {
xxTrxLogEnd.setPreviousValue(metaDataInfo);
}
trxLogListEnd.add(xxTrxLogEnd);
bizUtil.createTrxLog(trxLogListEnd);
if (LOG.isDebugEnabled()) {
LOG.debug("<== ServiceREST.importPoliciesFromFile()");
}
}
}
use of org.apache.ranger.security.context.RangerAdminOpContext in project ranger by apache.
the class ServiceREST method deleteServiceById.
private String deleteServiceById(Long id) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> ServiceREST.deleteServiceById( " + id + ")");
}
RangerAdminOpContext opContext = new RangerAdminOpContext();
opContext.setBulkModeContext(true);
RangerContextHolder.setOpContext(opContext);
RangerPerfTracer perf = null;
String deletedServiceName = null;
try {
if (RangerPerfTracer.isPerfTraceEnabled(PERF_LOG)) {
perf = RangerPerfTracer.getPerfTracer(PERF_LOG, "ServiceREST.deleteService(serviceId=" + id + ")");
}
RangerServiceValidator validator = validatorFactory.getServiceValidator(svcStore);
validator.validate(id, Action.DELETE);
UserSessionBase session = ContextUtil.getCurrentUserSession();
if (session != null) {
XXService service = daoManager.getXXService().getById(id);
if (service != null) {
// if logged-in user is not the service creator then check admin priv.
if (!session.getUserId().equals(service.getAddedByUserId())) {
bizUtil.hasAdminPermissions("Services");
}
EmbeddedServiceDefsUtil embeddedServiceDefsUtil = EmbeddedServiceDefsUtil.instance();
if (service.getType().equals(embeddedServiceDefsUtil.getTagServiceDefId())) {
List<XXService> referringServices = daoManager.getXXService().findByTagServiceId(id);
if (!CollectionUtils.isEmpty(referringServices)) {
Set<String> referringServiceNames = new HashSet<String>();
for (XXService xXService : referringServices) {
referringServiceNames.add(xXService.getName());
if (referringServiceNames.size() >= 10) {
break;
}
}
if (referringServices.size() <= 10) {
throw restErrorUtil.createRESTException("Tag service '" + service.getName() + "' is being referenced by " + referringServices.size() + " services: " + referringServiceNames, MessageEnums.OPER_NOT_ALLOWED_FOR_STATE);
} else {
throw restErrorUtil.createRESTException("Tag service '" + service.getName() + "' is being referenced by " + referringServices.size() + " services: " + referringServiceNames + " and more..", MessageEnums.OPER_NOT_ALLOWED_FOR_STATE);
}
}
}
XXServiceDef xxServiceDef = daoManager.getXXServiceDef().getById(service.getType());
if (!session.getUserId().equals(service.getAddedByUserId())) {
bizUtil.hasKMSPermissions("Service", xxServiceDef.getImplclassname());
bizUtil.blockAuditorRoleUser();
}
tagStore.deleteAllTagObjectsForService(service.getName());
deletedServiceName = service.getName();
svcStore.deleteService(id);
} else {
LOG.error("Cannot retrieve service:[" + id + "] for deletion");
throw new Exception("deleteService(" + id + ") failed");
}
} else {
LOG.error("Cannot retrieve user session.");
throw new Exception("deleteService(" + id + ") failed");
}
} catch (WebApplicationException excp) {
throw excp;
} catch (Throwable excp) {
LOG.error("deleteService(" + id + ") failed", excp);
throw restErrorUtil.createRESTException(excp.getMessage());
} finally {
RangerPerfTracer.log(perf);
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== ServiceREST.deleteServiceById() - deletedServiceName=" + deletedServiceName);
}
return deletedServiceName;
}
Aggregations