http://git-wip-us.apache.org/repos/asf/sentry/blob/f1332300/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/persistent/PrivilegeObject.java ---------------------------------------------------------------------- diff --git a/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/persistent/PrivilegeObject.java b/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/persistent/PrivilegeObject.java deleted file mode 100644 index feab1e9..0000000 --- a/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/persistent/PrivilegeObject.java +++ /dev/null @@ -1,231 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.sentry.provider.db.generic.service.persistent; - -import static org.apache.sentry.core.common.utils.SentryConstants.KV_JOINER; -import static org.apache.sentry.core.common.utils.SentryConstants.AUTHORIZABLE_JOINER; - -import java.util.List; -import org.apache.sentry.core.common.Authorizable; -import com.google.common.base.Preconditions; -import com.google.common.collect.Lists; - -public final class PrivilegeObject { - private final String component; - private final String service; - private final String action; - private final Boolean grantOption; - private List<? extends Authorizable> authorizables; - - private PrivilegeObject(String component, String service, String action, - Boolean grantOption, - List<? extends Authorizable> authorizables) { - this.component = component; - this.service = service; - this.action = action; - this.grantOption = grantOption; - this.authorizables = authorizables; - } - - public List<? extends Authorizable> getAuthorizables() { - return authorizables; - } - - public String getAction() { - return action; - } - - public String getComponent() { - return component; - } - - public String getService() { - return service; - } - - public Boolean getGrantOption() { - return grantOption; - } - - @Override - public String toString() { - List<String> authorizable = Lists.newArrayList(); - for (Authorizable az : authorizables) { - authorizable.add(KV_JOINER.join(az.getTypeName(),az.getName())); - } - return "PrivilegeObject [" + ", service=" + service + ", component=" - + component + ", authorizables=" + AUTHORIZABLE_JOINER.join(authorizable) - + ", action=" + action + ", grantOption=" + grantOption + "]"; - } - - @Override - public int hashCode() { - final int prime = 31; - int result = 1; - result = prime * result + ((action == null) ? 0 : action.hashCode()); - result = prime * result + ((component == null) ? 0 : component.hashCode()); - result = prime * result + ((service == null) ? 0 : service.hashCode()); - result = prime * result + ((grantOption == null) ? 0 : grantOption.hashCode()); - for (Authorizable authorizable : authorizables) { - result = prime * result + authorizable.getTypeName().hashCode(); - result = prime * result + authorizable.getName().hashCode(); - } - return result; - } - - @Override - public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (obj == null) { - return false; - } - if (getClass() != obj.getClass()) { - return false; - } - PrivilegeObject other = (PrivilegeObject) obj; - if (action == null) { - if (other.action != null) { - return false; - } - } else if (!action.equals(other.action)) { - return false; - } - if (service == null) { - if (other.service != null) { - return false; - } - } else if (!service.equals(other.service)) { - return false; - } - if (component == null) { - if (other.component != null) { - return false; - } - } else if (!component.equals(other.component)) { - return false; - } - if (grantOption == null) { - if (other.grantOption != null) { - return false; - } - } else if (!grantOption.equals(other.grantOption)) { - return false; - } - - if (authorizables.size() != other.authorizables.size()) { - return false; - } - for (int i = 0; i < authorizables.size(); i++) { - String o1 = KV_JOINER.join(authorizables.get(i).getTypeName(), - authorizables.get(i).getName()); - String o2 = KV_JOINER.join(other.authorizables.get(i).getTypeName(), - other.authorizables.get(i).getName()); - if (!o1.equalsIgnoreCase(o2)) { - return false; - } - } - return true; - } - - public static class Builder { - private String component; - private String service; - private String action; - private Boolean grantOption; - private List<? extends Authorizable> authorizables; - - public Builder() { - - } - - public Builder(PrivilegeObject privilege) { - this.component = privilege.component; - this.service = privilege.service; - this.action = privilege.action; - this.grantOption = privilege.grantOption; - this.authorizables = privilege.authorizables; - } - - public Builder setComponent(String component) { - this.component = component; - return this; - } - - public Builder setService(String service) { - this.service = service; - return this; - } - - public Builder setAction(String action) { - this.action = action; - return this; - } - - public Builder withGrantOption(Boolean grantOption) { - this.grantOption = grantOption; - return this; - } - - public Builder setAuthorizables(List<? extends Authorizable> authorizables) { - this.authorizables = authorizables; - return this; - } - - /** - * TolowerCase the authorizable name, the authorizable type is define when it was created. - * Take the Solr for example, it has two Authorizable objects. They have the type Collection - * and Field, they are can't be changed. So we should unified the authorizable name tolowercase. - * @return new authorizable lists - */ - private List<? extends Authorizable> toLowerAuthorizableName(List<? extends Authorizable> authorizables) { - List<Authorizable> newAuthorizable = Lists.newArrayList(); - if (authorizables == null || authorizables.size() == 0) { - return newAuthorizable; - } - for (final Authorizable authorizable : authorizables) { - newAuthorizable.add(new Authorizable() { - @Override - public String getTypeName() { - return authorizable.getTypeName(); - } - @Override - public String getName() { - return authorizable.getName(); - } - }); - } - return newAuthorizable; - } - - public PrivilegeObject build() { - Preconditions.checkNotNull(component); - Preconditions.checkNotNull(service); - Preconditions.checkNotNull(action); - //CaseInsensitive authorizable name - List<? extends Authorizable> newAuthorizable = toLowerAuthorizableName(authorizables); - - return new PrivilegeObject(component.toLowerCase(), - service.toLowerCase(), - action.toLowerCase(), - grantOption, - newAuthorizable); - } - } -}
http://git-wip-us.apache.org/repos/asf/sentry/blob/f1332300/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/persistent/PrivilegeOperatePersistence.java ---------------------------------------------------------------------- diff --git a/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/persistent/PrivilegeOperatePersistence.java b/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/persistent/PrivilegeOperatePersistence.java deleted file mode 100644 index fa9dadf..0000000 --- a/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/persistent/PrivilegeOperatePersistence.java +++ /dev/null @@ -1,485 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.sentry.provider.db.generic.service.persistent; - -import java.lang.reflect.Constructor; -import java.util.ArrayList; -import java.util.LinkedList; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import javax.jdo.PersistenceManager; -import javax.jdo.Query; - -import org.apache.hadoop.conf.Configuration; -import org.apache.sentry.core.common.exception.SentryUserException; -import org.apache.sentry.core.common.Action; -import org.apache.sentry.core.common.Authorizable; -import org.apache.sentry.core.common.BitFieldAction; -import org.apache.sentry.core.common.BitFieldActionFactory; -import org.apache.sentry.core.model.kafka.KafkaActionFactory; -import org.apache.sentry.core.model.search.SearchActionFactory; -import org.apache.sentry.core.model.sqoop.SqoopActionFactory; -import org.apache.sentry.provider.db.generic.service.persistent.PrivilegeObject.Builder; -import org.apache.sentry.provider.db.service.model.MSentryGMPrivilege; -import org.apache.sentry.provider.db.service.model.MSentryRole; - -import com.google.common.base.Joiner; -import com.google.common.base.Strings; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; -import org.apache.sentry.service.thrift.ServiceConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -/** - * This class used do some operations related privilege and make the results - * persistence - */ -public class PrivilegeOperatePersistence { - private static final Logger LOGGER = LoggerFactory.getLogger(PrivilegeOperatePersistence.class); - private static final Map<String, BitFieldActionFactory> actionFactories = Maps.newHashMap(); - static{ - actionFactories.put("solr", new SearchActionFactory()); - actionFactories.put("sqoop", new SqoopActionFactory()); - actionFactories.put("kafka", KafkaActionFactory.getInstance()); - } - - private final Configuration conf; - - public PrivilegeOperatePersistence(Configuration conf) { - this.conf = conf; - } - - public boolean checkPrivilegeOption(Set<MSentryRole> roles, PrivilegeObject privilege, PersistenceManager pm) { - MSentryGMPrivilege requestPrivilege = convertToPrivilege(privilege); - boolean hasGrant = false; - //get persistent privileges by roles - Query query = pm.newQuery(MSentryGMPrivilege.class); - StringBuilder filters = new StringBuilder(); - if (roles != null && roles.size() > 0) { - query.declareVariables("org.apache.sentry.provider.db.service.model.MSentryRole role"); - List<String> rolesFiler = new LinkedList<String>(); - for (MSentryRole role : roles) { - rolesFiler.add("role.roleName == \"" + role.getRoleName() + "\" "); - } - filters.append("roles.contains(role) " + "&& (" + Joiner.on(" || ").join(rolesFiler) + ")"); - } - query.setFilter(filters.toString()); - - List<MSentryGMPrivilege> tPrivileges = (List<MSentryGMPrivilege>)query.execute(); - for (MSentryGMPrivilege tPrivilege : tPrivileges) { - if (tPrivilege.getGrantOption() && tPrivilege.implies(requestPrivilege)) { - hasGrant = true; - break; - } - } - return hasGrant; - } - public void grantPrivilege(PrivilegeObject privilege,MSentryRole role, PersistenceManager pm) throws SentryUserException { - MSentryGMPrivilege mPrivilege = convertToPrivilege(privilege); - grantRolePartial(mPrivilege, role, pm); - } - - private void grantRolePartial(MSentryGMPrivilege grantPrivilege, - MSentryRole role,PersistenceManager pm) { - /** - * If Grant is for ALL action and other actions belongs to ALL action already exists.. - * need to remove it and GRANT ALL action - */ - String component = grantPrivilege.getComponentName(); - BitFieldAction action = getAction(component, grantPrivilege.getAction()); - BitFieldAction allAction = getAction(component, Action.ALL); - - if (action.implies(allAction)) { - /** - * ALL action is a multi-bit set action that includes some actions such as INSERT,SELECT and CREATE. - */ - List<? extends BitFieldAction> actions = getActionFactory(component).getActionsByCode(allAction.getActionCode()); - for (BitFieldAction ac : actions) { - grantPrivilege.setAction(ac.getValue()); - MSentryGMPrivilege existPriv = getPrivilege(grantPrivilege, pm); - if (existPriv != null && role.getGmPrivileges().contains(existPriv)) { - /** - * force to load all roles related this privilege - * avoid the lazy-loading risk,such as: - * if the roles field of privilege aren't loaded, then the roles is a empty set - * privilege.removeRole(role) and pm.makePersistent(privilege) - * will remove other roles that shouldn't been removed - */ - pm.retrieve(existPriv); - existPriv.removeRole(role); - pm.makePersistent(existPriv); - } - } - } else { - /** - * If ALL Action already exists.. - * do nothing. - */ - grantPrivilege.setAction(allAction.getValue()); - MSentryGMPrivilege allPrivilege = getPrivilege(grantPrivilege, pm); - if (allPrivilege != null && role.getGmPrivileges().contains(allPrivilege)) { - return; - } - } - - /** - * restore the action - */ - grantPrivilege.setAction(action.getValue()); - /** - * check the privilege is exist or not - */ - MSentryGMPrivilege mPrivilege = getPrivilege(grantPrivilege, pm); - if (mPrivilege == null) { - mPrivilege = grantPrivilege; - } - mPrivilege.appendRole(role); - pm.makePersistent(mPrivilege); - } - - - public void revokePrivilege(PrivilegeObject privilege,MSentryRole role, PersistenceManager pm) throws SentryUserException { - MSentryGMPrivilege mPrivilege = getPrivilege(convertToPrivilege(privilege), pm); - if (mPrivilege == null) { - mPrivilege = convertToPrivilege(privilege); - } else { - mPrivilege = (MSentryGMPrivilege) pm.detachCopy(mPrivilege); - } - - Set<MSentryGMPrivilege> privilegeGraph = Sets.newHashSet(); - privilegeGraph.addAll(populateIncludePrivileges(Sets.newHashSet(role), mPrivilege, pm)); - - /** - * Get the privilege graph - * populateIncludePrivileges will get the privileges that needed revoke - */ - for (MSentryGMPrivilege persistedPriv : privilegeGraph) { - /** - * force to load all roles related this privilege - * avoid the lazy-loading risk,such as: - * if the roles field of privilege aren't loaded, then the roles is a empty set - * privilege.removeRole(role) and pm.makePersistent(privilege) - * will remove other roles that shouldn't been removed - */ - revokeRolePartial(mPrivilege, persistedPriv, role, pm); - } - pm.makePersistent(role); - } - - /** - * Explore Privilege graph and collect privileges that are belong to the specific privilege - */ - @SuppressWarnings("unchecked") - private Set<MSentryGMPrivilege> populateIncludePrivileges(Set<MSentryRole> roles, - MSentryGMPrivilege parent, PersistenceManager pm) { - Set<MSentryGMPrivilege> childrens = Sets.newHashSet(); - - Query query = pm.newQuery(MSentryGMPrivilege.class); - StringBuilder filters = new StringBuilder(); - //add populateIncludePrivilegesQuery - filters.append(MSentryGMPrivilege.populateIncludePrivilegesQuery(parent)); - // add filter for role names - if (roles != null && roles.size() > 0) { - query.declareVariables("org.apache.sentry.provider.db.service.model.MSentryRole role"); - List<String> rolesFiler = new LinkedList<String>(); - for (MSentryRole role : roles) { - rolesFiler.add("role.roleName == \"" + role.getRoleName() + "\" "); - } - filters.append("&& roles.contains(role) " + "&& (" + Joiner.on(" || ").join(rolesFiler) + ")"); - } - query.setFilter(filters.toString()); - - List<MSentryGMPrivilege> privileges = (List<MSentryGMPrivilege>)query.execute(); - childrens.addAll(privileges); - return childrens; - } - - /** - * Roles can be granted multi-bit set action like ALL action on resource object. - * Take solr component for example, When a role has been granted ALL action but - * QUERY or UPDATE or CREATE are revoked, we need to remove the ALL - * privilege and add left privileges like UPDATE and CREATE(QUERY was revoked) or - * QUERY and UPDATE(CREATEE was revoked). - */ - private void revokeRolePartial(MSentryGMPrivilege revokePrivilege, - MSentryGMPrivilege persistedPriv, MSentryRole role, - PersistenceManager pm) { - String component = revokePrivilege.getComponentName(); - BitFieldAction revokeaction = getAction(component, revokePrivilege.getAction()); - BitFieldAction persistedAction = getAction(component, persistedPriv.getAction()); - BitFieldAction allAction = getAction(component, Action.ALL); - - if (revokeaction.implies(allAction)) { - /** - * if revoke action is ALL, directly revoke its children privileges and itself - */ - persistedPriv.removeRole(role); - pm.makePersistent(persistedPriv); - } else { - /** - * if persisted action is ALL, it only revoke the requested action and left partial actions - * like the requested action is SELECT, the UPDATE and CREATE action are left - */ - if (persistedAction.implies(allAction)) { - /** - * revoke the ALL privilege - */ - persistedPriv.removeRole(role); - pm.makePersistent(persistedPriv); - - List<? extends BitFieldAction> actions = getActionFactory(component).getActionsByCode(allAction.getActionCode()); - for (BitFieldAction ac: actions) { - if (ac.getActionCode() != revokeaction.getActionCode()) { - /** - * grant the left privileges to role - */ - MSentryGMPrivilege tmpPriv = new MSentryGMPrivilege(persistedPriv); - tmpPriv.setAction(ac.getValue()); - MSentryGMPrivilege leftPersistedPriv = getPrivilege(tmpPriv, pm); - if (leftPersistedPriv == null) { - //leftPersistedPriv isn't exist - leftPersistedPriv = tmpPriv; - role.appendGMPrivilege(leftPersistedPriv); - } - leftPersistedPriv.appendRole(role); - pm.makePersistent(leftPersistedPriv); - } - } - } else if (revokeaction.implies(persistedAction)) { - /** - * if the revoke action is equal to the persisted action and they aren't ALL action - * directly remove the role from privilege - */ - persistedPriv.removeRole(role); - pm.makePersistent(persistedPriv); - } - /** - * if the revoke action is not equal to the persisted action, - * do nothing - */ - } - } - - /** - * Drop any role related to the requested privilege and its children privileges - */ - public void dropPrivilege(PrivilegeObject privilege,PersistenceManager pm) { - MSentryGMPrivilege requestPrivilege = convertToPrivilege(privilege); - - if (Strings.isNullOrEmpty(privilege.getAction())) { - requestPrivilege.setAction(getAction(privilege.getComponent(), Action.ALL).getValue()); - } - /** - * Get the privilege graph - * populateIncludePrivileges will get the privileges that need dropped, - */ - Set<MSentryGMPrivilege> privilegeGraph = Sets.newHashSet(); - privilegeGraph.addAll(populateIncludePrivileges(null, requestPrivilege, pm)); - - for (MSentryGMPrivilege mPrivilege : privilegeGraph) { - /** - * force to load all roles related this privilege - * avoid the lazy-loading - */ - pm.retrieve(mPrivilege); - Set<MSentryRole> roles = mPrivilege.getRoles(); - for (MSentryRole role : roles) { - revokeRolePartial(requestPrivilege, mPrivilege, role, pm); - } - } - } - - private MSentryGMPrivilege convertToPrivilege(PrivilegeObject privilege) { - return new MSentryGMPrivilege(privilege.getComponent(), - privilege.getService(), privilege.getAuthorizables(), - privilege.getAction(), privilege.getGrantOption()); - } - - private MSentryGMPrivilege getPrivilege(MSentryGMPrivilege privilege, PersistenceManager pm) { - Query query = pm.newQuery(MSentryGMPrivilege.class); - query.setFilter(MSentryGMPrivilege.toQuery(privilege)); - query.setUnique(true); - return (MSentryGMPrivilege)query.execute(); - } - - @SuppressWarnings("unchecked") - public Set<PrivilegeObject> getPrivilegesByRole(Set<MSentryRole> roles, PersistenceManager pm) { - Set<PrivilegeObject> privileges = Sets.newHashSet(); - if (roles == null || roles.size() == 0) { - return privileges; - } - Query query = pm.newQuery(MSentryGMPrivilege.class); - StringBuilder filters = new StringBuilder(); - // add filter for role names - query.declareVariables("org.apache.sentry.provider.db.service.model.MSentryRole role"); - List<String> rolesFiler = new LinkedList<String>(); - for (MSentryRole role : roles) { - rolesFiler.add("role.roleName == \"" + role.getRoleName() + "\" "); - } - filters.append("roles.contains(role) " + "&& (" + Joiner.on(" || ").join(rolesFiler) + ")"); - - query.setFilter(filters.toString()); - List<MSentryGMPrivilege> mPrivileges = (List<MSentryGMPrivilege>) query.execute(); - if (mPrivileges == null || mPrivileges.isEmpty()) { - return privileges; - } - for (MSentryGMPrivilege mPrivilege : mPrivileges) { - privileges.add(new Builder() - .setComponent(mPrivilege.getComponentName()) - .setService(mPrivilege.getServiceName()) - .setAction(mPrivilege.getAction()) - .setAuthorizables(mPrivilege.getAuthorizables()) - .withGrantOption(mPrivilege.getGrantOption()) - .build()); - } - return privileges; - } - - public Set<PrivilegeObject> getPrivilegesByProvider(String component, - String service, Set<MSentryRole> roles, - List<? extends Authorizable> authorizables, PersistenceManager pm) { - Set<PrivilegeObject> privileges = Sets.newHashSet(); - if (roles == null || roles.isEmpty()) { - return privileges; - } - - MSentryGMPrivilege parentPrivilege = new MSentryGMPrivilege(component, service, authorizables, null, null); - Set<MSentryGMPrivilege> privilegeGraph = Sets.newHashSet(); - privilegeGraph.addAll(populateIncludePrivileges(roles, parentPrivilege, pm)); - - for (MSentryGMPrivilege mPrivilege : privilegeGraph) { - privileges.add(new Builder() - .setComponent(mPrivilege.getComponentName()) - .setService(mPrivilege.getServiceName()) - .setAction(mPrivilege.getAction()) - .setAuthorizables(mPrivilege.getAuthorizables()) - .withGrantOption(mPrivilege.getGrantOption()) - .build()); - } - return privileges; - } - - public Set<MSentryGMPrivilege> getPrivilegesByAuthorizable(String component, - String service, Set<MSentryRole> roles, - List<? extends Authorizable> authorizables, PersistenceManager pm) { - - Set<MSentryGMPrivilege> privilegeGraph = Sets.newHashSet(); - - if (roles == null || roles.isEmpty()) { - return privilegeGraph; - } - - MSentryGMPrivilege parentPrivilege = new MSentryGMPrivilege(component, service, authorizables, null, null); - privilegeGraph.addAll(populateIncludePrivileges(roles, parentPrivilege, pm)); - return privilegeGraph; - } - - public void renamePrivilege(String component, String service, - List<? extends Authorizable> oldAuthorizables, List<? extends Authorizable> newAuthorizables, - String grantorPrincipal, PersistenceManager pm) - throws SentryUserException { - MSentryGMPrivilege oldPrivilege = new MSentryGMPrivilege(component, service, oldAuthorizables, null, null); - oldPrivilege.setAction(getAction(component,Action.ALL).getValue()); - /** - * Get the privilege graph - * populateIncludePrivileges will get the old privileges that need dropped - */ - Set<MSentryGMPrivilege> privilegeGraph = Sets.newHashSet(); - privilegeGraph.addAll(populateIncludePrivileges(null, oldPrivilege, pm)); - - for (MSentryGMPrivilege dropPrivilege : privilegeGraph) { - /** - * construct the new privilege needed to add - */ - List<Authorizable> authorizables = new ArrayList<Authorizable>( - dropPrivilege.getAuthorizables()); - for (int i = 0; i < newAuthorizables.size(); i++) { - authorizables.set(i, newAuthorizables.get(i)); - } - MSentryGMPrivilege newPrivilge = new MSentryGMPrivilege( - component,service, authorizables, dropPrivilege.getAction(), - dropPrivilege.getGrantOption()); - - /** - * force to load all roles related this privilege - * avoid the lazy-loading - */ - pm.retrieve(dropPrivilege); - - Set<MSentryRole> roles = dropPrivilege.getRoles(); - for (MSentryRole role : roles) { - revokeRolePartial(oldPrivilege, dropPrivilege, role, pm); - grantRolePartial(newPrivilge, role, pm); - } - } - } - - private BitFieldAction getAction(String component, String name) { - BitFieldActionFactory actionFactory = getActionFactory(component); - BitFieldAction action = actionFactory.getActionByName(name); - if (action == null) { - throw new RuntimeException("Can not get BitFieldAction for name: " + name); - } - return action; - } - - private BitFieldActionFactory getActionFactory(String component) { - String caseInsensitiveComponent = component.toLowerCase(); - if (actionFactories.containsKey(caseInsensitiveComponent)) { - return actionFactories.get(caseInsensitiveComponent); - } - BitFieldActionFactory actionFactory = createActionFactory(caseInsensitiveComponent); - actionFactories.put(caseInsensitiveComponent, actionFactory); - LOGGER.info("Action factory for component {} is not found in cache. Loaded it from configuration as {}.", - component, actionFactory.getClass().getName()); - return actionFactory; - } - - private BitFieldActionFactory createActionFactory(String component) { - String actionFactoryClassName = - conf.get(String.format(ServiceConstants.ServerConfig.SENTRY_COMPONENT_ACTION_FACTORY_FORMAT, component)); - if (actionFactoryClassName == null) { - throw new RuntimeException("ActionFactory not defined for component " + component + - ". Please define the parameter " + - "sentry." + component + ".action.factory in configuration"); - } - Class<?> actionFactoryClass; - try { - actionFactoryClass = Class.forName(actionFactoryClassName); - } catch (ClassNotFoundException e) { - throw new RuntimeException("ActionFactory class " + actionFactoryClassName + " not found."); - } - if (!BitFieldActionFactory.class.isAssignableFrom(actionFactoryClass)) { - throw new RuntimeException("ActionFactory class " + actionFactoryClassName + " must extend " - + BitFieldActionFactory.class.getName()); - } - BitFieldActionFactory actionFactory; - try { - Constructor<?> actionFactoryConstructor = actionFactoryClass.getDeclaredConstructor(); - actionFactoryConstructor.setAccessible(true); - actionFactory = (BitFieldActionFactory) actionFactoryClass.newInstance(); - } catch (NoSuchMethodException | InstantiationException | IllegalAccessException e) { - throw new RuntimeException("Could not instantiate actionFactory " + actionFactoryClassName + - " for component: " + component, e); - } - return actionFactory; - } -} http://git-wip-us.apache.org/repos/asf/sentry/blob/f1332300/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/persistent/SentryStoreLayer.java ---------------------------------------------------------------------- diff --git a/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/persistent/SentryStoreLayer.java b/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/persistent/SentryStoreLayer.java deleted file mode 100644 index c003965..0000000 --- a/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/persistent/SentryStoreLayer.java +++ /dev/null @@ -1,198 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.sentry.provider.db.generic.service.persistent; - -import java.util.List; -import java.util.Set; - -import org.apache.sentry.core.common.exception.SentryUserException; -import org.apache.sentry.core.common.Authorizable; -import org.apache.sentry.core.common.exception.SentryAlreadyExistsException; -import org.apache.sentry.core.common.exception.SentryNoSuchObjectException; -import org.apache.sentry.provider.db.service.model.MSentryGMPrivilege; -import org.apache.sentry.provider.db.service.persistent.CommitContext; - -/** - * Sentry store for persistent the authorize object to database - */ -public interface SentryStoreLayer { - /** - * Create a role - * @param component: The request respond to which component - * @param role: The name of role - * @param requestor: User on whose behalf the request is launched - * @returns commit context used for notification handlers - * @throws SentryAlreadyExistsException - */ - CommitContext createRole(String component, String role, - String requestor) throws SentryAlreadyExistsException; - - /** - * Drop a role - * @param component: The request respond to which component - * @param role: The name of role - * @param requestor: user on whose behalf the request is launched - * @returns commit context used for notification handlers - * @throws SentryNoSuchObjectException - */ - CommitContext dropRole(String component, String role, - String requestor) throws SentryNoSuchObjectException; - - /** - * Add a role to groups. - * @param component: The request respond to which component - * @param role: The name of role - * @param groups: The name of groups - * @param requestor: User on whose behalf the request is issued - * @returns commit context used for notification handlers - * @throws SentryNoSuchObjectException - */ - CommitContext alterRoleAddGroups(String component, String role, - Set<String> groups, String requestor) throws SentryNoSuchObjectException; - - /** - * Delete a role from groups. - * @param component: The request respond to which component - * @param role: The name of role - * @param groups: The name of groups - * @param requestor: User on whose behalf the request is launched - * @returns commit context used for notification handlers - * @throws SentryNoSuchObjectException - */ - CommitContext alterRoleDeleteGroups(String component, String role, - Set<String> groups, String requestor) throws SentryNoSuchObjectException; - - /** - * Grant a privilege to role. - * @param component: The request respond to which component - * @param role: The name of role - * @param privilege: The privilege object will be granted - * @param grantorPrincipal: User on whose behalf the request is launched - * @returns commit context Used for notification handlers - * @throws SentryUserException - */ - CommitContext alterRoleGrantPrivilege(String component, String role, - PrivilegeObject privilege, String grantorPrincipal) throws SentryUserException; - - /** - * Revoke a privilege from role. - * @param component: The request respond to which component - * @param role: The name of role - * @param privilege: The privilege object will revoked - * @param grantorPrincipal: User on whose behalf the request is launched - * @returns commit context used for notification handlers - * @throws SentryUserException - */ - CommitContext alterRoleRevokePrivilege(String component, String role, - PrivilegeObject privilege, String grantorPrincipal) throws SentryUserException; - - /** - * Rename privilege - * - * @param component: The request respond to which component - * @param service: The name of service - * @param oldAuthorizables: The old list of authorize objects - * @param newAuthorizables: The new list of authorize objects - * @param requestor: User on whose behalf the request is launched - * @returns commit context used for notification handlers - * @throws SentryUserException - */ - CommitContext renamePrivilege( - String component, String service, List<? extends Authorizable> oldAuthorizables, - List<? extends Authorizable> newAuthorizables, String requestor) throws SentryUserException; - - /** - * Drop privilege - * @param component: The request respond to which component - * @param privilege: The privilege will be dropped - * @param requestor: User on whose behalf the request is launched - * @returns commit context used for notification handlers - * @throws SentryUserException - */ - CommitContext dropPrivilege(String component, PrivilegeObject privilege, - String requestor) throws SentryUserException; - - /** - * Get roles - * @param component: The request respond to which component - * @param groups: The name of groups - * @returns the set of roles - * @throws SentryUserException - */ - Set<String> getRolesByGroups(String component, Set<String> groups) throws SentryUserException; - - /** - * Get groups - * @param component: The request respond to which component - * @param roles: The name of roles - * @returns the set of groups - * @throws SentryUserException - */ - Set<String> getGroupsByRoles(String component, Set<String> roles) throws SentryUserException; - - /** - * Get privileges - * @param component: The request respond to which component - * @param roles: The name of roles - * @returns the set of privileges - * @throws SentryUserException - */ - Set<PrivilegeObject> getPrivilegesByRole(String component, Set<String> roles) throws SentryUserException; - - /** - * get sentry privileges from provider as followings: - * @param component: The request respond to which component - * @param service: The name of service - * @param roles: The name of roles - * @param groups: The name of groups - * @param authorizables: The list of authorize objects - * @returns the set of privileges - * @throws SentryUserException - */ - - Set<PrivilegeObject> getPrivilegesByProvider(String component, String service, Set<String> roles, - Set<String> groups, List<? extends Authorizable> authorizables) - throws SentryUserException; - - /** - * Get all roles name. - * - * @returns The set of roles name, - */ - Set<String> getAllRoleNames(); - - /** - * Get sentry privileges based on valid active roles and the authorize objects. - * - * @param component: The request respond to which component - * @param service: The name of service - * @param validActiveRoles: The valid active roles - * @param authorizables: The list of authorize objects - * @returns The set of MSentryGMPrivilege - * @throws SentryUserException - */ - Set<MSentryGMPrivilege> getPrivilegesByAuthorizable(String component, String service, - Set<String> validActiveRoles, List<? extends Authorizable> authorizables) - throws SentryUserException; - - /** - * close sentryStore - */ - void close(); - -} http://git-wip-us.apache.org/repos/asf/sentry/blob/f1332300/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/NotificationHandler.java ---------------------------------------------------------------------- diff --git a/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/NotificationHandler.java b/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/NotificationHandler.java deleted file mode 100644 index e0a5f03..0000000 --- a/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/NotificationHandler.java +++ /dev/null @@ -1,47 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.sentry.provider.db.generic.service.thrift; - -import org.apache.sentry.provider.db.service.persistent.CommitContext; - -public interface NotificationHandler { - - void create_sentry_role(CommitContext context, - TCreateSentryRoleRequest request, TCreateSentryRoleResponse response); - - void drop_sentry_role(CommitContext context, TDropSentryRoleRequest request, - TDropSentryRoleResponse response); - - void alter_sentry_role_grant_privilege(CommitContext context, TAlterSentryRoleGrantPrivilegeRequest request, - TAlterSentryRoleGrantPrivilegeResponse response); - - void alter_sentry_role_revoke_privilege(CommitContext context, TAlterSentryRoleRevokePrivilegeRequest request, - TAlterSentryRoleRevokePrivilegeResponse response); - - void alter_sentry_role_add_groups(CommitContext context,TAlterSentryRoleAddGroupsRequest request, - TAlterSentryRoleAddGroupsResponse response); - - void alter_sentry_role_delete_groups(CommitContext context, TAlterSentryRoleDeleteGroupsRequest request, - TAlterSentryRoleDeleteGroupsResponse response); - - void drop_sentry_privilege(CommitContext context, TDropPrivilegesRequest request, - TDropPrivilegesResponse response); - - void rename_sentry_privilege(CommitContext context, TRenamePrivilegesRequest request, - TRenamePrivilegesResponse response); -} http://git-wip-us.apache.org/repos/asf/sentry/blob/f1332300/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/NotificationHandlerInvoker.java ---------------------------------------------------------------------- diff --git a/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/NotificationHandlerInvoker.java b/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/NotificationHandlerInvoker.java deleted file mode 100644 index 1d9c246..0000000 --- a/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/NotificationHandlerInvoker.java +++ /dev/null @@ -1,164 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.sentry.provider.db.generic.service.thrift; - -import java.util.List; - -import org.apache.sentry.provider.db.service.persistent.CommitContext; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.collect.Lists; - -/** - * Invokes configured instances of NotificationHandler. Importantly - * NotificationHandler's each receive a copy of the request and - * response thrift objects from each successful request. - */ -public class NotificationHandlerInvoker implements NotificationHandler { - private static final Logger LOGGER = LoggerFactory.getLogger(NotificationHandlerInvoker.class); - private List<? extends NotificationHandler> handlers = Lists.newArrayList(); - - public NotificationHandlerInvoker(List<? extends NotificationHandler> handlers) { - this.handlers = handlers; - } - @Override - public void create_sentry_role(CommitContext context, - TCreateSentryRoleRequest request, TCreateSentryRoleResponse response) { - for (NotificationHandler handler : handlers) { - try { - LOGGER.debug("Calling " + handler); - handler.create_sentry_role(context, new TCreateSentryRoleRequest(request), - new TCreateSentryRoleResponse(response)); - } catch (Exception ex) { - LOGGER.error("Unexpected error in " + handler + ". Request: " - + request + ", Response: " + response, ex); - } - } - } - - @Override - public void drop_sentry_role(CommitContext context, - TDropSentryRoleRequest request, TDropSentryRoleResponse response) { - for (NotificationHandler handler : handlers) { - try { - LOGGER.debug("Calling " + handler); - handler.drop_sentry_role(context, new TDropSentryRoleRequest(request), - new TDropSentryRoleResponse(response)); - } catch (Exception ex) { - LOGGER.error("Unexpected error in " + handler + ". Request: " - + request + ", Response: " + response, ex); - } - } - } - - @Override - public void alter_sentry_role_grant_privilege(CommitContext context, - TAlterSentryRoleGrantPrivilegeRequest request, - TAlterSentryRoleGrantPrivilegeResponse response) { - for (NotificationHandler handler : handlers) { - try { - LOGGER.debug("Calling " + handler); - handler.alter_sentry_role_grant_privilege(context, - new TAlterSentryRoleGrantPrivilegeRequest(request), - new TAlterSentryRoleGrantPrivilegeResponse(response)); - } catch (Exception ex) { - LOGGER.error("Unexpected error in " + handler + ". Request: " - + request + ", Response: " + response, ex); - } - } - } - - @Override - public void alter_sentry_role_revoke_privilege(CommitContext context, - TAlterSentryRoleRevokePrivilegeRequest request, - TAlterSentryRoleRevokePrivilegeResponse response) { - for (NotificationHandler handler : handlers) { - try { - LOGGER.debug("Calling " + handler); - handler.alter_sentry_role_revoke_privilege(context, - new TAlterSentryRoleRevokePrivilegeRequest(request), - new TAlterSentryRoleRevokePrivilegeResponse(response)); - } catch (Exception ex) { - LOGGER.error("Unexpected error in " + handler + ". Request: " - + request + ", Response: " + response, ex); - } - } - } - - @Override - public void alter_sentry_role_add_groups(CommitContext context, - TAlterSentryRoleAddGroupsRequest request, - TAlterSentryRoleAddGroupsResponse response) { - for (NotificationHandler handler : handlers) { - try { - LOGGER.debug("Calling " + handler); - handler.alter_sentry_role_add_groups(context, new TAlterSentryRoleAddGroupsRequest(request), - new TAlterSentryRoleAddGroupsResponse(response)); - } catch (Exception ex) { - LOGGER.error("Unexpected error in " + handler + ". Request: " - + request + ", Response: " + response, ex); - } - } - } - - @Override - public void alter_sentry_role_delete_groups(CommitContext context, - TAlterSentryRoleDeleteGroupsRequest request, - TAlterSentryRoleDeleteGroupsResponse response) { - for (NotificationHandler handler : handlers) { - try { - LOGGER.debug("Calling " + handler); - handler.alter_sentry_role_delete_groups(context, new TAlterSentryRoleDeleteGroupsRequest(request), - new TAlterSentryRoleDeleteGroupsResponse(response)); - } catch (Exception ex) { - LOGGER.error("Unexpected error in " + handler + ". Request: " - + request + ", Response: " + response, ex); - } - } - } - @Override - public void drop_sentry_privilege(CommitContext context, - TDropPrivilegesRequest request, TDropPrivilegesResponse response) { - for (NotificationHandler handler : handlers) { - try { - LOGGER.debug("Calling " + handler); - handler.drop_sentry_privilege(context, new TDropPrivilegesRequest(request), - new TDropPrivilegesResponse(response)); - } catch (Exception ex) { - LOGGER.error("Unexpected error in " + handler + ". Request: " - + request + ", Response: " + response, ex); - } - } - } - @Override - public void rename_sentry_privilege(CommitContext context, - TRenamePrivilegesRequest request, TRenamePrivilegesResponse response) { - for (NotificationHandler handler : handlers) { - try { - LOGGER.debug("Calling " + handler); - handler.rename_sentry_privilege(context, new TRenamePrivilegesRequest(request), - new TRenamePrivilegesResponse(response)); - } catch (Exception ex) { - LOGGER.error("Unexpected error in " + handler + ". Request: " - + request + ", Response: " + response, ex); - } - } - } - -} http://git-wip-us.apache.org/repos/asf/sentry/blob/f1332300/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/SentryGenericPolicyProcessor.java ---------------------------------------------------------------------- diff --git a/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/SentryGenericPolicyProcessor.java b/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/SentryGenericPolicyProcessor.java deleted file mode 100644 index 04e7ea9..0000000 --- a/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/SentryGenericPolicyProcessor.java +++ /dev/null @@ -1,836 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.sentry.provider.db.generic.service.thrift; - -import static org.apache.sentry.core.common.utils.SentryConstants.AUTHORIZABLE_JOINER; -import static org.apache.sentry.core.common.utils.SentryConstants.KV_JOINER; - -import java.lang.reflect.Constructor; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -import org.apache.hadoop.conf.Configuration; -import org.apache.sentry.core.common.exception.SentryUserException; -import org.apache.sentry.core.common.Authorizable; -import org.apache.sentry.core.common.utils.SentryConstants; -import org.apache.sentry.core.common.exception.SentrySiteConfigurationException; -import org.apache.sentry.core.model.db.AccessConstants; -import org.apache.sentry.core.common.utils.KeyValue; -import org.apache.sentry.provider.common.AuthorizationComponent; -import org.apache.sentry.core.common.exception.SentryAccessDeniedException; -import org.apache.sentry.core.common.exception.SentryAlreadyExistsException; -import org.apache.sentry.core.common.exception.SentryInvalidInputException; -import org.apache.sentry.core.common.exception.SentryNoSuchObjectException; -import org.apache.sentry.core.common.exception.SentryThriftAPIMismatchException; -import org.apache.sentry.provider.db.generic.service.persistent.PrivilegeObject; -import org.apache.sentry.provider.db.generic.service.persistent.PrivilegeObject.Builder; -import org.apache.sentry.provider.db.generic.service.persistent.SentryStoreLayer; -import org.apache.sentry.provider.db.log.entity.JsonLogEntityFactory; -import org.apache.sentry.provider.db.log.util.Constants; -import org.apache.sentry.provider.db.service.model.MSentryGMPrivilege; -import org.apache.sentry.provider.db.service.model.MSentryRole; -import org.apache.sentry.provider.db.service.persistent.CommitContext; -import org.apache.sentry.provider.db.service.thrift.PolicyStoreConstants; -import org.apache.sentry.provider.db.service.thrift.SentryPolicyStoreProcessor; -import org.apache.sentry.service.thrift.ServiceConstants.ServerConfig; -import org.apache.sentry.service.thrift.ServiceConstants.ThriftConstants; -import org.apache.sentry.service.thrift.ServiceConstants; -import org.apache.sentry.service.thrift.Status; -import org.apache.sentry.service.thrift.TSentryResponseStatus; -import org.apache.thrift.TException; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import com.google.common.annotations.VisibleForTesting; -import com.google.common.base.Splitter; -import com.google.common.base.Strings; -import com.google.common.collect.ImmutableSet; -import com.google.common.collect.Lists; -import com.google.common.collect.Maps; -import com.google.common.collect.Sets; - -public class SentryGenericPolicyProcessor implements SentryGenericPolicyService.Iface { - private static final Logger LOGGER = LoggerFactory.getLogger(SentryGenericPolicyProcessor.class); - private static final Logger AUDIT_LOGGER = LoggerFactory - .getLogger(Constants.AUDIT_LOGGER_NAME_GENERIC); - private final Configuration conf; - private final ImmutableSet<String> adminGroups; - private final SentryStoreLayer store; - private final NotificationHandlerInvoker handerInvoker; - - public static final String SENTRY_GENERIC_SERVICE_NAME = "SentryGenericPolicyService"; - private static final String ACCESS_DENIAL_MESSAGE = "Access denied to "; - - public SentryGenericPolicyProcessor(Configuration conf) throws Exception { - this.store = createStore(conf); - this.handerInvoker = new NotificationHandlerInvoker(createHandlers(conf)); - this.conf = conf; - adminGroups = ImmutableSet.copyOf((Sets.newHashSet(conf.getStrings( - ServerConfig.ADMIN_GROUPS, new String[]{})))); - } - - @VisibleForTesting - public SentryGenericPolicyProcessor(Configuration conf, SentryStoreLayer store) throws Exception { - this.store = store; - this.handerInvoker = new NotificationHandlerInvoker(createHandlers(conf)); - this.conf = conf; - adminGroups = ImmutableSet.copyOf(toTrimmed(Sets.newHashSet(conf.getStrings( - ServerConfig.ADMIN_GROUPS, new String[]{})))); - } - - private void authorize(String requestorUser, Set<String> requestorGroups) - throws SentryAccessDeniedException { - if (!inAdminGroups(requestorGroups)) { - String msg = "User: " + requestorUser + " is part of " + requestorGroups + - " which does not, intersect admin groups " + adminGroups; - LOGGER.warn(msg); - throw new SentryAccessDeniedException(ACCESS_DENIAL_MESSAGE + requestorUser); - } - } - - private Set<String> toTrimmedLower(Set<String> s) { - if (null == s) { - return new HashSet<String>(); - } - Set<String> result = Sets.newHashSet(); - for (String v : s) { - result.add(v.trim().toLowerCase()); - } - return result; - } - - private Set<String> toTrimmed(Set<String> s) { - if (null == s) { - return new HashSet<String>(); - } - Set<String> result = Sets.newHashSet(); - for (String v : s) { - result.add(v.trim()); - } - return result; - } - - private String toTrimmedLower(String s) { - if (Strings.isNullOrEmpty(s)){ - return ""; - } - return s.trim().toLowerCase(); - } - - public static Set<String> getRequestorGroups(Configuration conf, String userName) throws SentryUserException { - return SentryPolicyStoreProcessor.getGroupsFromUserName(conf, userName); - } - - private boolean inAdminGroups(Set<String> requestorGroups) { - if (Sets.intersection(adminGroups, requestorGroups).isEmpty()) { - return false; - } - return true; - } - - public static SentryStoreLayer createStore(Configuration conf) throws SentrySiteConfigurationException { - SentryStoreLayer storeLayer = null; - String store = conf.get(PolicyStoreConstants.SENTRY_GENERIC_POLICY_STORE, PolicyStoreConstants.SENTRY_GENERIC_POLICY_STORE_DEFAULT); - - if (Strings.isNullOrEmpty(store)) { - throw new SentrySiteConfigurationException("sentry.generic.policy.store can not be empty"); - } - try { - storeLayer = createInstance(store, conf, SentryStoreLayer.class); - } catch (Exception e) { - throw new SentrySiteConfigurationException("Create sentryStore error: " + e.getMessage(), e); - } - return storeLayer; - } - - public static List<NotificationHandler> createHandlers(Configuration conf) throws SentrySiteConfigurationException { - - List<NotificationHandler> handlers = Lists.newArrayList(); - Iterable<String> notificationHandlers = Splitter.onPattern("[\\s,]").trimResults() - .omitEmptyStrings().split(conf.get(PolicyStoreConstants.SENTRY_GENERIC_POLICY_NOTIFICATION, "")); - try { - for (String notificationHandler : notificationHandlers) { - handlers.add(createInstance(notificationHandler, conf, NotificationHandler.class)); - } - } catch (Exception e) { - throw new SentrySiteConfigurationException("Create notificationHandlers error: " + e.getMessage(), e); - } - return handlers; - } - - @SuppressWarnings("unchecked") - public static <T> T createInstance(String className, Configuration conf, Class<T> iface) throws Exception { - T result; - try { - Class<?> clazz = Class.forName(className); - if (!iface.isAssignableFrom(clazz)) { - throw new IllegalArgumentException("Class " + clazz + " is not a " + - iface.getName()); - } - Constructor<T> meth = (Constructor<T>)clazz.getDeclaredConstructor(Configuration.class); - meth.setAccessible(true); - result = meth.newInstance(new Object[]{conf}); - } catch (Exception e) { - throw new RuntimeException(e); - } - return result; - } - - private <T> Response<T> requestHandle(RequestHandler<T> handler) { - Response<T> response = new Response<T>(); - try { - response = handler.handle(); - } catch (SentryAccessDeniedException e) { - String msg = "Sentry access denied: " + e.getMessage(); - LOGGER.error(msg, e); - response.status = Status.AccessDenied(e.getMessage(), e); - } catch (SentryAlreadyExistsException e) { - String msg = "Sentry object already exists: " + e.getMessage(); - LOGGER.error(msg, e); - response.status = Status.AlreadyExists(e.getMessage(), e); - } catch (SentryNoSuchObjectException e) { - String msg = "Sentry object doesn't exist: " + e.getMessage(); - LOGGER.error(msg, e); - response.status = Status.NoSuchObject(e.getMessage(), e); - } catch (SentryInvalidInputException e) { - String msg = "Invalid input privilege object: " + e.getMessage(); - LOGGER.error(msg, e); - response.status = Status.InvalidInput(msg, e); - } catch (SentryThriftAPIMismatchException e) { - String msg = "Sentry thrift API mismatch error: " + e.getMessage(); - LOGGER.error(msg, e); - response.status = Status.THRIFT_VERSION_MISMATCH(e.getMessage(), e); - } catch (Exception e) { - String msg = "Unknown error:" + e.getMessage(); - LOGGER.error(msg, e); - response.status = Status.RuntimeError(msg, e); - } - return response; - } - - private PrivilegeObject toPrivilegeObject(TSentryPrivilege tSentryPrivilege) { - Boolean grantOption; - if (tSentryPrivilege.getGrantOption().equals(TSentryGrantOption.TRUE)) { - grantOption = true; - } else if (tSentryPrivilege.getGrantOption().equals(TSentryGrantOption.FALSE)) { - grantOption = false; - } else { - grantOption = null; - } - return new Builder().setComponent(tSentryPrivilege.getComponent()) - .setService(tSentryPrivilege.getServiceName()) - .setAuthorizables(toAuthorizables(tSentryPrivilege.getAuthorizables())) - .setAction(tSentryPrivilege.getAction()) - .withGrantOption(grantOption) - .build(); - } - - private TSentryPrivilege fromPrivilegeObject(PrivilegeObject privilege) { - - TSentryPrivilege tPrivilege = new TSentryPrivilege(privilege.getComponent(), privilege.getService(), - fromAuthorizable(privilege.getAuthorizables()), - privilege.getAction()); - if (privilege.getGrantOption() == null) { - tPrivilege.setGrantOption(TSentryGrantOption.UNSET); - } else if (privilege.getGrantOption()) { - tPrivilege.setGrantOption(TSentryGrantOption.TRUE); - } else { - tPrivilege.setGrantOption(TSentryGrantOption.FALSE); - } - return tPrivilege; - } - - private List<TAuthorizable> fromAuthorizable(List<? extends Authorizable> authorizables) { - List<TAuthorizable> tAuthorizables = Lists.newArrayList(); - for (Authorizable authorizable : authorizables) { - tAuthorizables.add(new TAuthorizable(authorizable.getTypeName(), authorizable.getName())); - } - return tAuthorizables; - } - - private String fromAuthorizableToStr(List<? extends Authorizable> authorizables) { - if (authorizables != null && !authorizables.isEmpty()) { - List<String> privileges = Lists.newArrayList(); - - for (Authorizable authorizable : authorizables) { - - privileges.add(SentryConstants.KV_JOINER.join(authorizable.getTypeName(), - authorizable.getName())); - } - - return SentryConstants.AUTHORIZABLE_JOINER.join(privileges); - } else { - return ""; - } - } - - private List<? extends Authorizable> toAuthorizables(List<TAuthorizable> tAuthorizables) { - List<Authorizable> authorizables = Lists.newArrayList(); - if (tAuthorizables == null) { - return authorizables; - } - for (final TAuthorizable tAuthorizable : tAuthorizables) { - authorizables.add(new Authorizable() { - @Override - public String getTypeName() { - return tAuthorizable.getType(); - } - @Override - public String getName() { - return tAuthorizable.getName(); - } - }); - } - return authorizables; - } - - private List<? extends Authorizable> toAuthorizables(String privilegeStr) { - List<Authorizable> authorizables = Lists.newArrayList(); - if (privilegeStr == null) { - return authorizables; - } - - for (String authorizable : SentryConstants.AUTHORIZABLE_SPLITTER.split(privilegeStr)) { - KeyValue tempKV = new KeyValue(authorizable); - final String key = tempKV.getKey(); - final String value = tempKV.getValue(); - - authorizables.add(new Authorizable() { - @Override - public String getTypeName() { - return key; - } - - @Override - public String getName() { - return value; - } - }); - } - - return authorizables; - } - - // Construct the role to set of privileges mapping based on the - // MSentryGMPrivilege information. - private TSentryPrivilegeMap toTSentryPrivilegeMap(Set<MSentryGMPrivilege> mPrivileges) { - - // Mapping of <Role, Set<Privilege>>. - Map<String, Set<TSentryPrivilege>> tPrivilegeMap = Maps.newTreeMap(); - - for (MSentryGMPrivilege mPrivilege : mPrivileges) { - for (MSentryRole role : mPrivilege.getRoles()) { - - TSentryPrivilege tPrivilege = toTSentryPrivilege(mPrivilege); - - if (tPrivilegeMap.containsKey(role.getRoleName())) { - tPrivilegeMap.get(role.getRoleName()).add(tPrivilege); - } else { - Set<TSentryPrivilege> tPrivilegeSet = Sets.newTreeSet(); - tPrivilegeSet.add(tPrivilege); - tPrivilegeMap.put(role.getRoleName(), tPrivilegeSet); - } - } - } - - return new TSentryPrivilegeMap(tPrivilegeMap); - } - - // Construct TSentryPrivilege based on MSentryGMPrivilege information. - private TSentryPrivilege toTSentryPrivilege(MSentryGMPrivilege mPrivilege) { - - TSentryPrivilege tPrivilege = new TSentryPrivilege(mPrivilege.getComponentName(), - mPrivilege.getServiceName(), fromAuthorizable(mPrivilege.getAuthorizables()), mPrivilege.getAction()); - - if (mPrivilege.getGrantOption() == null) { - tPrivilege.setGrantOption(TSentryGrantOption.UNSET); - } else if (mPrivilege.getGrantOption()) { - tPrivilege.setGrantOption(TSentryGrantOption.TRUE); - } else { - tPrivilege.setGrantOption(TSentryGrantOption.FALSE); - } - - return tPrivilege; - } - - private Set<String> buildPermissions(Set<PrivilegeObject> privileges) { - Set<String> permissions = Sets.newHashSet(); - for (PrivilegeObject privilege : privileges) { - List<String> hierarchy = Lists.newArrayList(); - if (hasComponentServerPrivilege(privilege.getComponent())) { - hierarchy.add(KV_JOINER.join("server", privilege.getService())); - } - for (Authorizable authorizable : privilege.getAuthorizables()) { - hierarchy.add(KV_JOINER.join(authorizable.getTypeName(),authorizable.getName())); - } - hierarchy.add(KV_JOINER.join("action", privilege.getAction())); - permissions.add(AUTHORIZABLE_JOINER.join(hierarchy)); - } - return permissions; - } - - private boolean hasComponentServerPrivilege(String component) { - //judge the component whether has the server privilege, for example: sqoop has the privilege on the server - return AuthorizationComponent.SQOOP.equalsIgnoreCase(component); - } - - @Override - public TCreateSentryRoleResponse create_sentry_role( - final TCreateSentryRoleRequest request) throws TException { - Response<Void> respose = requestHandle(new RequestHandler<Void>() { - @Override - public Response<Void> handle() throws Exception { - validateClientVersion(request.getProtocol_version()); - authorize(request.getRequestorUserName(), - getRequestorGroups(conf, request.getRequestorUserName())); - CommitContext context = store.createRole(request.getComponent(), request.getRoleName(), request.getRequestorUserName()); - return new Response<Void>(Status.OK(), context); - } - }); - - TCreateSentryRoleResponse tResponse = new TCreateSentryRoleResponse(respose.status); - if (Status.OK.getCode() == respose.status.getValue()) { - handerInvoker.create_sentry_role(respose.context, request, tResponse); - } - - try { - AUDIT_LOGGER.info(JsonLogEntityFactory.getInstance() - .createJsonLogEntity(request, tResponse, conf).toJsonFormatLog()); - } catch (Exception e) { - // if any exception, log the exception. - String msg = "Error in creating audit log for create role: " + e.getMessage(); - LOGGER.error(msg, e); - } - return tResponse; - } - - @Override - public TDropSentryRoleResponse drop_sentry_role(final TDropSentryRoleRequest request) - throws TException { - Response<Void> respose = requestHandle(new RequestHandler<Void>() { - @Override - public Response<Void> handle() throws Exception { - validateClientVersion(request.getProtocol_version()); - authorize(request.getRequestorUserName(), - getRequestorGroups(conf, request.getRequestorUserName())); - CommitContext context = store.dropRole(request.getComponent(), request.getRoleName(), request.getRequestorUserName()); - return new Response<Void>(Status.OK(), context); - } - }); - - TDropSentryRoleResponse tResponse = new TDropSentryRoleResponse(respose.status); - if (Status.OK.getCode() == respose.status.getValue()) { - handerInvoker.drop_sentry_role(respose.context, request, tResponse); - } - - try { - AUDIT_LOGGER.info(JsonLogEntityFactory.getInstance() - .createJsonLogEntity(request, tResponse, conf).toJsonFormatLog()); - } catch (Exception e) { - // if any exception, log the exception. - String msg = "Error in creating audit log for drop role: " + e.getMessage(); - LOGGER.error(msg, e); - } - return tResponse; - } - - @Override - public TAlterSentryRoleGrantPrivilegeResponse alter_sentry_role_grant_privilege( - final TAlterSentryRoleGrantPrivilegeRequest request) throws TException { - Response<Void> respose = requestHandle(new RequestHandler<Void>() { - @Override - public Response<Void> handle() throws Exception { - validateClientVersion(request.getProtocol_version()); - CommitContext context = store.alterRoleGrantPrivilege(request.getComponent(), request.getRoleName(), toPrivilegeObject(request.getPrivilege()), request.getRequestorUserName()); - return new Response<Void>(Status.OK(), context); - } - }); - - TAlterSentryRoleGrantPrivilegeResponse tResponse = new TAlterSentryRoleGrantPrivilegeResponse(respose.status); - if (Status.OK.getCode() == respose.status.getValue()) { - handerInvoker.alter_sentry_role_grant_privilege(respose.context, request, tResponse); - } - - try { - AUDIT_LOGGER.info(JsonLogEntityFactory.getInstance() - .createJsonLogEntity(request, tResponse, conf).toJsonFormatLog()); - } catch (Exception e) { - // if any exception, log the exception. - String msg = "Error in creating audit log for grant privilege to role: " + e.getMessage(); - LOGGER.error(msg, e); - } - return tResponse; - } - - @Override - public TAlterSentryRoleRevokePrivilegeResponse alter_sentry_role_revoke_privilege( - final TAlterSentryRoleRevokePrivilegeRequest request) throws TException { - Response<Void> respose = requestHandle(new RequestHandler<Void>() { - @Override - public Response<Void> handle() throws Exception { - validateClientVersion(request.getProtocol_version()); - CommitContext context = store.alterRoleRevokePrivilege(request.getComponent(), request.getRoleName(), toPrivilegeObject(request.getPrivilege()), request.getRequestorUserName()); - return new Response<Void>(Status.OK(), context); - } - }); - - TAlterSentryRoleRevokePrivilegeResponse tResponse = new TAlterSentryRoleRevokePrivilegeResponse(respose.status); - if (Status.OK.getCode() == respose.status.getValue()) { - handerInvoker.alter_sentry_role_revoke_privilege(respose.context, request, tResponse); - } - - try { - AUDIT_LOGGER.info(JsonLogEntityFactory.getInstance() - .createJsonLogEntity(request, tResponse, conf).toJsonFormatLog()); - } catch (Exception e) { - // if any exception, log the exception. - String msg = "Error in creating audit log for revoke privilege from role: " + e.getMessage(); - LOGGER.error(msg, e); - } - return tResponse; - } - - @Override - public TAlterSentryRoleAddGroupsResponse alter_sentry_role_add_groups( - final TAlterSentryRoleAddGroupsRequest request) throws TException { - Response<Void> respose = requestHandle(new RequestHandler<Void>() { - @Override - public Response<Void> handle() throws Exception { - validateClientVersion(request.getProtocol_version()); - authorize(request.getRequestorUserName(), - getRequestorGroups(conf, request.getRequestorUserName())); - CommitContext context = store.alterRoleAddGroups(request.getComponent(), request.getRoleName(), request.getGroups(), request.getRequestorUserName()); - return new Response<Void>(Status.OK(), context); - } - }); - - TAlterSentryRoleAddGroupsResponse tResponse = new TAlterSentryRoleAddGroupsResponse(respose.status); - if (Status.OK.getCode() == respose.status.getValue()) { - handerInvoker.alter_sentry_role_add_groups(respose.context, request, tResponse); - } - - try { - AUDIT_LOGGER.info(JsonLogEntityFactory.getInstance() - .createJsonLogEntity(request, tResponse, conf).toJsonFormatLog()); - } catch (Exception e) { - // if any exception, log the exception. - String msg = "Error in creating audit log for add role to group: " + e.getMessage(); - LOGGER.error(msg, e); - } - return tResponse; - } - - @Override - public TAlterSentryRoleDeleteGroupsResponse alter_sentry_role_delete_groups( - final TAlterSentryRoleDeleteGroupsRequest request) throws TException { - Response<Void> respose = requestHandle(new RequestHandler<Void>() { - @Override - public Response<Void> handle() throws Exception { - validateClientVersion(request.getProtocol_version()); - authorize(request.getRequestorUserName(), - getRequestorGroups(conf, request.getRequestorUserName())); - CommitContext context = store.alterRoleDeleteGroups(request.getComponent(), request.getRoleName(), request.getGroups(), request.getRequestorUserName()); - return new Response<Void>(Status.OK(), context); - } - }); - - TAlterSentryRoleDeleteGroupsResponse tResponse = new TAlterSentryRoleDeleteGroupsResponse(respose.status); - if (Status.OK.getCode() == respose.status.getValue()) { - handerInvoker.alter_sentry_role_delete_groups(respose.context, request, tResponse); - } - - try { - AUDIT_LOGGER.info(JsonLogEntityFactory.getInstance() - .createJsonLogEntity(request, tResponse, conf).toJsonFormatLog()); - } catch (Exception e) { - // if any exception, log the exception. - String msg = "Error in creating audit log for delete role from group: " + e.getMessage(); - LOGGER.error(msg, e); - } - return tResponse; - } - - @Override - public TListSentryRolesResponse list_sentry_roles_by_group( - final TListSentryRolesRequest request) throws TException { - Response<Set<TSentryRole>> respose = requestHandle(new RequestHandler<Set<TSentryRole>>() { - @Override - public Response<Set<TSentryRole>> handle() throws Exception { - validateClientVersion(request.getProtocol_version()); - Set<String> groups = getRequestorGroups(conf, request.getRequestorUserName()); - if (!AccessConstants.ALL.equalsIgnoreCase(request.getGroupName())) { - boolean admin = inAdminGroups(groups); - //Only admin users can list all roles in the system ( groupname = null) - //Non admin users are only allowed to list only groups which they belong to - if(!admin && (request.getGroupName() == null || !groups.contains(request.getGroupName()))) { - throw new SentryAccessDeniedException(ACCESS_DENIAL_MESSAGE + request.getRequestorUserName()); - } - groups.clear(); - groups.add(request.getGroupName()); - } - - Set<String> roleNames = store.getRolesByGroups(request.getComponent(), groups); - Set<TSentryRole> tSentryRoles = Sets.newHashSet(); - for (String roleName : roleNames) { - Set<String> groupsForRoleName = store.getGroupsByRoles(request.getComponent(), Sets.newHashSet(roleName)); - tSentryRoles.add(new TSentryRole(roleName, groupsForRoleName)); - } - return new Response<Set<TSentryRole>>(Status.OK(), tSentryRoles); - } - }); - TListSentryRolesResponse tResponse = new TListSentryRolesResponse(); - tResponse.setStatus(respose.status); - tResponse.setRoles(respose.content); - return tResponse; - } - - @Override - public TListSentryPrivilegesResponse list_sentry_privileges_by_role( - final TListSentryPrivilegesRequest request) throws TException { - Response<Set<TSentryPrivilege>> respose = requestHandle(new RequestHandler<Set<TSentryPrivilege>>() { - @Override - public Response<Set<TSentryPrivilege>> handle() throws Exception { - validateClientVersion(request.getProtocol_version()); - Set<String> groups = getRequestorGroups(conf, request.getRequestorUserName()); - if (!inAdminGroups(groups)) { - Set<String> roleNamesForGroups = toTrimmedLower(store.getRolesByGroups(request.getComponent(), groups)); - if (!roleNamesForGroups.contains(toTrimmedLower(request.getRoleName()))) { - throw new SentryAccessDeniedException(ACCESS_DENIAL_MESSAGE + request.getRequestorUserName()); - } - } - Set<PrivilegeObject> privileges = store.getPrivilegesByProvider(request.getComponent(), - request.getServiceName(), - Sets.newHashSet(request.getRoleName()), - null, toAuthorizables(request.getAuthorizables())); - Set<TSentryPrivilege> tSentryPrivileges = Sets.newHashSet(); - for (PrivilegeObject privilege : privileges) { - tSentryPrivileges.add(fromPrivilegeObject(privilege)); - } - return new Response<Set<TSentryPrivilege>>(Status.OK(), tSentryPrivileges); - } - }); - TListSentryPrivilegesResponse tResponse = new TListSentryPrivilegesResponse(); - tResponse.setStatus(respose.status); - tResponse.setPrivileges(respose.content); - return tResponse; - } - - @Override - public TListSentryPrivilegesForProviderResponse list_sentry_privileges_for_provider( - final TListSentryPrivilegesForProviderRequest request) throws TException { - Response<Set<String>> respose = requestHandle(new RequestHandler<Set<String>>() { - @Override - public Response<Set<String>> handle() throws Exception { - validateClientVersion(request.getProtocol_version()); - Set<String> activeRoleNames = toTrimmedLower(request.getRoleSet().getRoles()); - Set<String> roleNamesForGroups = store.getRolesByGroups(request.getComponent(), request.getGroups()); - Set<String> rolesToQuery = request.getRoleSet().isAll() ? roleNamesForGroups : Sets.intersection(activeRoleNames, roleNamesForGroups); - Set<PrivilegeObject> privileges = store.getPrivilegesByProvider(request.getComponent(), - request.getServiceName(), - rolesToQuery, null, - toAuthorizables(request.getAuthorizables())); - return new Response<Set<String>>(Status.OK(), buildPermissions(privileges)); - } - }); - TListSentryPrivilegesForProviderResponse tResponse = new TListSentryPrivilegesForProviderResponse(); - tResponse.setStatus(respose.status); - tResponse.setPrivileges(respose.content); - return tResponse; - } - - @Override - public TListSentryPrivilegesByAuthResponse list_sentry_privileges_by_authorizable(TListSentryPrivilegesByAuthRequest request) throws TException { - - TListSentryPrivilegesByAuthResponse response = new TListSentryPrivilegesByAuthResponse(); - Map<String, TSentryPrivilegeMap> authRoleMap = Maps.newHashMap(); - - // Group names are case sensitive. - Set<String> requestedGroups = request.getGroups(); - String subject = request.getRequestorUserName(); - TSentryActiveRoleSet activeRoleSet = request.getRoleSet(); - Set<String> validActiveRoles = Sets.newHashSet(); - - try { - validateClientVersion(request.getProtocol_version()); - Set<String> memberGroups = getRequestorGroups(conf, subject); - - // Disallow non-admin users to lookup groups that - // they are not part of. - if(!inAdminGroups(memberGroups)) { - - if (requestedGroups != null && !requestedGroups.isEmpty()) { - for (String requestedGroup : requestedGroups) { - - // If user doesn't belong to one of the requested groups, - // then raise security exception. - if (!memberGroups.contains(requestedGroup)) { - throw new SentryAccessDeniedException(ACCESS_DENIAL_MESSAGE + subject); - } - } - } else { - // Non-admin's search is limited to its own groups. - requestedGroups = memberGroups; - } - - Set<String> grantedRoles = toTrimmedLower(store.getRolesByGroups(request.getComponent(), requestedGroups)); - - // If activeRoleSet is not null, disallow non-admin to lookup roles that they are not part of. - if (activeRoleSet != null && !activeRoleSet.isAll()) { - - Set<String> activeRoleNames = toTrimmedLower(activeRoleSet.getRoles()); - for (String activeRole : activeRoleNames) { - if (!grantedRoles.contains(activeRole)) { - throw new SentryAccessDeniedException(ACCESS_DENIAL_MESSAGE - + subject); - } - } - - // For non-admin, valid active roles are intersection of active roles and granted roles. - validActiveRoles.addAll(activeRoleSet.isAll() ? grantedRoles : Sets.intersection(activeRoleNames, grantedRoles)); - } else { - // For non-admin, if activeRoleSet is null, valid active roles would be the granted roles. - validActiveRoles.addAll(grantedRoles); - } - } else { - // For admin, if requestedGroups are empty, requested roles will be all roles. - Set<String> requestedRoles = toTrimmedLower(store.getAllRoleNames()); - if (requestedGroups != null && !requestedGroups.isEmpty()) { - requestedRoles = toTrimmedLower(store.getRolesByGroups(request.getComponent(), requestedGroups)); - } - - // If activeRoleSet (which is optional) is not null, valid active role will be intersection - // of active roles and requested roles. Otherwise, valid active roles are the requested roles. - if (activeRoleSet != null && !activeRoleSet.isAll()) { - validActiveRoles.addAll(Sets.intersection(toTrimmedLower(activeRoleSet.getRoles()), requestedRoles)); - } else { - validActiveRoles.addAll(requestedRoles); - } - } - - // If user is not part of any group.. return empty response - if (request.getAuthorizablesSet() != null) { - for (String authorizablesStr : request.getAuthorizablesSet()) { - - List<? extends Authorizable> authorizables = toAuthorizables(authorizablesStr); - Set<MSentryGMPrivilege> sentryPrivileges = store.getPrivilegesByAuthorizable(request.getComponent(), request.getServiceName(), validActiveRoles, authorizables); - authRoleMap.put(fromAuthorizableToStr(authorizables), toTSentryPrivilegeMap(sentryPrivileges)); - } - } - - response.setPrivilegesMapByAuth(authRoleMap); - response.setStatus(Status.OK()); - } catch (SentryAccessDeniedException e) { - LOGGER.error(e.getMessage(), e); - response.setStatus(Status.AccessDenied(e.getMessage(), e)); - } catch (SentryThriftAPIMismatchException e) { - LOGGER.error(e.getMessage(), e); - response.setStatus(Status.THRIFT_VERSION_MISMATCH(e.getMessage(), e)); - } catch (Exception e) { - String msg = "Unknown error for request: " + request + ", message: " - + e.getMessage(); - LOGGER.error(msg, e); - response.setStatus(Status.RuntimeError(msg, e)); - } - - return response; - } - - @Override - public TDropPrivilegesResponse drop_sentry_privilege( - final TDropPrivilegesRequest request) throws TException { - Response<Void> respose = requestHandle(new RequestHandler<Void>() { - @Override - public Response<Void> handle() throws Exception { - validateClientVersion(request.getProtocol_version()); - authorize(request.getRequestorUserName(), - getRequestorGroups(conf, request.getRequestorUserName())); - CommitContext context = store.dropPrivilege(request.getComponent(), - toPrivilegeObject(request.getPrivilege()), - request.getRequestorUserName()); - return new Response<Void>(Status.OK(), context); - } - }); - - TDropPrivilegesResponse tResponse = new TDropPrivilegesResponse(respose.status); - if (Status.OK.getCode() == respose.status.getValue()) { - handerInvoker.drop_sentry_privilege(respose.context, request, tResponse); - } - return tResponse; - } - - @Override - public TRenamePrivilegesResponse rename_sentry_privilege( - final TRenamePrivilegesRequest request) throws TException { - Response<Void> respose = requestHandle(new RequestHandler<Void>() { - @Override - public Response<Void> handle() throws Exception { - validateClientVersion(request.getProtocol_version()); - authorize(request.getRequestorUserName(), - getRequestorGroups(conf, request.getRequestorUserName())); - CommitContext context = store.renamePrivilege(request.getComponent(), request.getServiceName(), - toAuthorizables(request.getOldAuthorizables()), - toAuthorizables(request.getNewAuthorizables()), - request.getRequestorUserName()); - return new Response<Void>(Status.OK(),context); - } - }); - - TRenamePrivilegesResponse tResponse = new TRenamePrivilegesResponse(respose.status); - if (Status.OK.getCode() == respose.status.getValue()) { - handerInvoker.rename_sentry_privilege(respose.context, request, tResponse); - } - return tResponse; - } - - private static class Response<T> { - private TSentryResponseStatus status; - private CommitContext context; - private T content; - - Response() { - } - - Response(TSentryResponseStatus status, CommitContext context) { - this(status,context,null); - } - - Response(TSentryResponseStatus status, T content) { - this(status,null,content); - } - - Response(TSentryResponseStatus status, CommitContext context, T content) { - this.status = status; - this.context = context; - this.content = content; - } - } - private interface RequestHandler <T>{ - Response<T> handle() throws Exception ; - } - - private static void validateClientVersion(int protocolVersion) throws SentryThriftAPIMismatchException { - if (ServiceConstants.ThriftConstants.TSENTRY_SERVICE_VERSION_CURRENT != protocolVersion) { - String msg = "Sentry thrift API protocol version mismatch: Client thrift version " + - "is: " + protocolVersion + " , server thrift version " + - "is " + ThriftConstants.TSENTRY_SERVICE_VERSION_CURRENT; - throw new SentryThriftAPIMismatchException(msg); - } - } -} http://git-wip-us.apache.org/repos/asf/sentry/blob/f1332300/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/SentryGenericPolicyProcessorFactory.java ---------------------------------------------------------------------- diff --git a/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/SentryGenericPolicyProcessorFactory.java b/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/SentryGenericPolicyProcessorFactory.java deleted file mode 100644 index 1cce1fc..0000000 --- a/sentry-provider/sentry-provider-db/src/main/java/org/apache/sentry/provider/db/generic/service/thrift/SentryGenericPolicyProcessorFactory.java +++ /dev/null @@ -1,40 +0,0 @@ -/** - * Licensed to the Apache Software Foundation (ASF) under one - * or more contributor license agreements. See the NOTICE file - * distributed with this work for additional information - * regarding copyright ownership. The ASF licenses this file - * to you under the Apache License, Version 2.0 (the - * "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -package org.apache.sentry.provider.db.generic.service.thrift; - -import org.apache.hadoop.conf.Configuration; -import org.apache.sentry.service.thrift.ProcessorFactory; -import org.apache.thrift.TMultiplexedProcessor; -import org.apache.thrift.TProcessor; - -public class SentryGenericPolicyProcessorFactory extends ProcessorFactory { - - public SentryGenericPolicyProcessorFactory(Configuration conf) { - super(conf); - } - - @Override - public boolean register(TMultiplexedProcessor multiplexedProcessor) throws Exception { - SentryGenericPolicyProcessor processHandler = new SentryGenericPolicyProcessor(conf); - TProcessor processor = new SentryGenericPolicyProcessorWrapper<SentryGenericPolicyService.Iface>( - processHandler); - multiplexedProcessor.registerProcessor(SentryGenericPolicyProcessor.SENTRY_GENERIC_SERVICE_NAME, processor); - return true; - } - -}
