下面列出了org.apache.hadoop.hbase.security.User#getShortName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void sendHBaseNameSpaceOperation(final NamespaceDescriptor namespaceDescriptor, final String nameSpace, final OPERATION operation, ObserverContext<MasterCoprocessorEnvironment> ctx) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> HBaseAtlasHook.sendHBaseNameSpaceOperation()");
}
try {
final UserGroupInformation ugi = getUGI(ctx);
final User user = getActiveUser(ctx);
final String userName = (user != null) ? user.getShortName() : null;
HBaseOperationContext hbaseOperationContext = handleHBaseNameSpaceOperation(namespaceDescriptor, nameSpace, operation, ugi, userName);
sendNotification(hbaseOperationContext);
} catch (Throwable t) {
LOG.error("HBaseAtlasHook.sendHBaseNameSpaceOperation(): failed to send notification", t);
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== HBaseAtlasHook.sendHBaseNameSpaceOperation()");
}
}
public void sendHBaseTableOperation(TableDescriptor tableDescriptor, final TableName tableName, final OPERATION operation, ObserverContext<MasterCoprocessorEnvironment> ctx) {
if (LOG.isDebugEnabled()) {
LOG.debug("==> HBaseAtlasHook.sendHBaseTableOperation()");
}
try {
final UserGroupInformation ugi = getUGI(ctx);
final User user = getActiveUser(ctx);
final String userName = (user != null) ? user.getShortName() : null;
HBaseOperationContext hbaseOperationContext = handleHBaseTableOperation(tableDescriptor, tableName, operation, ugi, userName);
sendNotification(hbaseOperationContext);
} catch (Throwable t) {
LOG.error("<== HBaseAtlasHook.sendHBaseTableOperation(): failed to send notification", t);
}
if (LOG.isDebugEnabled()) {
LOG.debug("<== HBaseAtlasHook.sendHBaseTableOperation()");
}
}
/**
* Checks that the user has the given global permission. The generated
* audit log message will contain context information for the operation
* being authorized, based on the given parameters.
*
* @param user Active user to which authorization checks should be applied
* @param request Request type
* @param perm Action being requested
* @param tableName Affected table name.
* @param familyMap Affected column families.
* @param filterUser User name to be filtered from permission as requested
*/
public void requireGlobalPermission(User user, String request,
Action perm, TableName tableName,
Map<byte[], ? extends Collection<byte[]>> familyMap, String filterUser) throws IOException {
AuthResult result;
if (authManager.authorizeUserGlobal(user, perm)) {
result = AuthResult.allow(request, "Global check allowed", user, perm, tableName, familyMap);
} else {
result = AuthResult.deny(request, "Global check failed", user, perm, tableName, familyMap);
}
result.getParams().setTableName(tableName).setFamilies(familyMap);
result.getParams().addExtraParam("filterUser", filterUser);
logResult(result);
if (!result.isAllowed()) {
throw new AccessDeniedException(
"Insufficient permissions for user '" + (user != null ? user.getShortName() : "null")
+ "' (global, action=" + perm.toString() + ")");
}
}
/**
* Checks that the user has the given global permission. The generated
* audit log message will contain context information for the operation
* being authorized, based on the given parameters.
*
* @param user Active user to which authorization checks should be applied
* @param request Request type
* @param perm Action being requested
* @param namespace The given namespace
*/
public void requireGlobalPermission(User user, String request, Action perm,
String namespace) throws IOException {
AuthResult authResult;
if (authManager.authorizeUserGlobal(user, perm)) {
authResult = AuthResult.allow(request, "Global check allowed", user, perm, null);
authResult.getParams().setNamespace(namespace);
logResult(authResult);
} else {
authResult = AuthResult.deny(request, "Global check failed", user, perm, null);
authResult.getParams().setNamespace(namespace);
logResult(authResult);
throw new AccessDeniedException(
"Insufficient permissions for user '" + (user != null ? user.getShortName() : "null")
+ "' (global, action=" + perm.toString() + ")");
}
}
protected void checkAccess() throws AccessDeniedException {
if (!spliceTable)
return;
if (!UserGroupInformation.isSecurityEnabled())
return;
User user = RpcServer.getRequestUser().get();
if (user == null || user.getShortName().equalsIgnoreCase("hbase"))
return;
if (RpcUtils.isAccessAllowed())
return;
if (!authTokenEnabled && authManager.authorize(user, Permission.Action.ADMIN))
return;
throw new AccessDeniedException("Insufficient permissions for user " +
user.getShortName());
}
protected void requireSystemOrSuperUser(Configuration conf, ObserverContext<?> ctx) throws IOException {
User user = User.getCurrent();
if (user == null) {
throw new IOException("Unable to obtain the current user, authorization checks for internal operations will not work correctly!");
}
String systemUser = user.getShortName();
User activeUser = getActiveUser(ctx);
if (!Objects.equals(systemUser, activeUser.getShortName()) && !_userUtils.isSuperUser(activeUser)) {
throw new AccessDeniedException("User '" + user.getShortName() + "is not system or super user.");
}
}
private void requireScannerOwner(ObserverContext<?> ctx, InternalScanner s) throws AccessDeniedException {
if (!RpcServer.isInRpcCallContext()) {
return;
}
User user = getActiveUser(ctx);
String requestUserName = user.getShortName();
String owner = scannerOwners.get(s);
if (owner != null && !owner.equals(requestUserName)) {
throw new AccessDeniedException("User '"+ requestUserName +"' is not the scanner owner!");
}
}
@Override
public RegionScanner postScannerOpen(ObserverContext<RegionCoprocessorEnvironment> c, Scan scan, RegionScanner s) throws IOException {
User user = getActiveUser(c);
if (user != null && user.getShortName() != null) {
scannerOwners.put(s, user.getShortName());
}
return s;
}
@Override
public String getUserAsString(User user) {
if (user == null) {
throw new IllegalArgumentException("User is null!");
}
else {
return user.getShortName();
}
}
private Path createStagingDir(Path baseDir, User user, TableName tableName) throws IOException {
String tblName = tableName.getNameAsString().replace(":", UNDERSCORE);
int RANDOM_WIDTH = 320;
int RANDOM_RADIX = 32;
String doubleUnderScore = UNDERSCORE + UNDERSCORE;
String randomDir = user.getShortName() + doubleUnderScore + tblName + doubleUnderScore
+ (new BigInteger(RANDOM_WIDTH, new SecureRandom()).toString(RANDOM_RADIX));
return createStagingDir(baseDir, user, randomDir);
}
@Override
public RegionScanner postScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
final Scan scan, final RegionScanner s) throws IOException {
User user = VisibilityUtils.getActiveUser();
if (user != null && user.getShortName() != null) {
scannerOwners.put(s, user.getShortName());
}
return s;
}
private void checkCallingUserAuth() throws IOException {
if (!authorizationEnabled) { // Redundant, but just in case
return;
}
if (!accessControllerAvailable) {
User user = VisibilityUtils.getActiveUser();
if (user == null) {
throw new IOException("Unable to retrieve calling user");
}
if (!(this.visibilityLabelService.havingSystemAuth(user))) {
throw new AccessDeniedException("User '" + user.getShortName()
+ "' is not authorized to perform this action.");
}
}
}
@Override
public List<String> getLabels(User user, Authorizations authorizations) {
if (authorizations != null) {
List<String> labels = authorizations.getLabels();
String userName = user.getShortName();
Set<String> auths = new HashSet<>();
auths.addAll(this.labelsCache.getUserAuths(userName));
auths.addAll(this.labelsCache.getGroupAuths(user.getGroupNames()));
return dropLabelsNotInUserAuths(labels, new ArrayList<>(auths), userName);
}
return null;
}
@Override
public List<String> getLabels(User user, Authorizations authorizations) {
if (authorizations == null || authorizations.getLabels() == null
|| authorizations.getLabels().isEmpty()) {
String userName = user.getShortName();
Set<String> auths = new HashSet<>();
auths.addAll(this.labelsCache.getUserAuths(userName));
auths.addAll(this.labelsCache.getGroupAuths(user.getGroupNames()));
return new ArrayList<>(auths);
}
return authorizations.getLabels();
}
@Override
public List<String> getLabels(User user, Authorizations authorizations) {
String userName = user.getShortName();
if (authorizations != null) {
LOG.warn("Dropping authorizations requested by user " + userName + ": " + authorizations);
}
Set<String> auths = new HashSet<>();
auths.addAll(this.labelsCache.getUserAuths(userName));
auths.addAll(this.labelsCache.getGroupAuths(user.getGroupNames()));
return new ArrayList<>(auths);
}
@Override
public RegionScanner postScannerOpen(final ObserverContext<RegionCoprocessorEnvironment> c,
final Scan scan, final RegionScanner s) throws IOException {
User user = getActiveUser(c);
if (user != null && user.getShortName() != null) {
// store reference to scanner owner for later checks
scannerOwners.put(s, user.getShortName());
}
return s;
}
private void checkSystemOrSuperUser(User activeUser) throws IOException {
// No need to check if we're not going to throw
if (!authorizationEnabled) {
return;
}
if (!Superusers.isSuperUser(activeUser)) {
throw new AccessDeniedException("User '" + (activeUser != null ?
activeUser.getShortName() : "null") + "' is not system or super user.");
}
}
private AccessTestAction grantPermissions(final String actions, final User user) throws SQLException {
return new AccessTestAction() {
@Override
public Object run() throws Exception {
try (Connection conn = getConnection(); Statement stmt = conn.createStatement();) {
String grantStmtSQL = "GRANT '" + actions + "' TO " + " '" + user.getShortName() + "'";
LOGGER.info("Grant Permissions SQL: " + grantStmtSQL);
assertFalse(stmt.execute(grantStmtSQL));
}
return null;
}
};
}
private GrantRevokeRequest createRevokeData(AccessControlProtos.RevokeRequest request) throws Exception {
AccessControlProtos.UserPermission up = request.getUserPermission();
AccessControlProtos.Permission perm = up == null ? null : up.getPermission();
UserPermission userPerm = up == null ? null : AccessControlUtil.toUserPermission(up);
String userName = userPerm == null ? null : Bytes.toString(userPerm.getUser());
String nameSpace = null;
String tableName = null;
String colFamily = null;
String qualifier = null;
if(perm == null) {
throw new Exception("revoke(): invalid data - permission is null");
}
if(StringUtil.isEmpty(userName)) {
throw new Exception("revoke(): invalid data - username empty");
}
switch(perm.getType()) {
case Global :
tableName = colFamily = qualifier = RangerHBaseResource.WILDCARD;
break;
case Table :
tableName = Bytes.toString(userPerm.getTableName().getName());
colFamily = Bytes.toString(userPerm.getFamily());
qualifier = Bytes.toString(userPerm.getQualifier());
break;
case Namespace:
nameSpace = userPerm.getNamespace();
break;
}
if(StringUtil.isEmpty(nameSpace) && StringUtil.isEmpty(tableName) && StringUtil.isEmpty(colFamily) && StringUtil.isEmpty(qualifier)) {
throw new Exception("revoke(): table/columnFamily/columnQualifier not specified");
}
tableName = StringUtil.isEmpty(tableName) ? RangerHBaseResource.WILDCARD : tableName;
colFamily = StringUtil.isEmpty(colFamily) ? RangerHBaseResource.WILDCARD : colFamily;
qualifier = StringUtil.isEmpty(qualifier) ? RangerHBaseResource.WILDCARD : qualifier;
if(! StringUtil.isEmpty(nameSpace)) {
tableName = nameSpace + RangerHBaseResource.NAMESPACE_SEPARATOR + tableName;
}
User activeUser = getActiveUser(null);
String grantor = activeUser != null ? activeUser.getShortName() : null;
String[] groups = activeUser != null ? activeUser.getGroupNames() : null;
Set<String> grantorGroups = null;
if (groups != null && groups.length > 0) {
grantorGroups = new HashSet<>(Arrays.asList(groups));
}
Map<String, String> mapResource = new HashMap<String, String>();
mapResource.put(RangerHBaseResource.KEY_TABLE, tableName);
mapResource.put(RangerHBaseResource.KEY_COLUMN_FAMILY, colFamily);
mapResource.put(RangerHBaseResource.KEY_COLUMN, qualifier);
GrantRevokeRequest ret = new GrantRevokeRequest();
ret.setGrantor(grantor);
ret.setGrantorGroups(grantorGroups);
ret.setDelegateAdmin(Boolean.TRUE); // remove delegateAdmin privilege as well
ret.setEnableAudit(Boolean.TRUE);
ret.setReplaceExistingPermissions(Boolean.TRUE);
ret.setResource(mapResource);
ret.setClientIPAddress(getRemoteAddress());
ret.setForwardedAddresses(null);//TODO: Need to check with Knox proxy how they handle forwarded add.
ret.setRemoteIPAddress(getRemoteAddress());
ret.setRequestData(up.toString());
if(userName.startsWith(GROUP_PREFIX)) {
ret.getGroups().add(userName.substring(GROUP_PREFIX.length()));
} else {
ret.getUsers().add(userName);
}
// revoke removes all permissions
ret.getAccessTypes().add(HbaseAuthUtils.ACCESS_TYPE_READ);
ret.getAccessTypes().add(HbaseAuthUtils.ACCESS_TYPE_WRITE);
ret.getAccessTypes().add(HbaseAuthUtils.ACCESS_TYPE_CREATE);
ret.getAccessTypes().add(HbaseAuthUtils.ACCESS_TYPE_ADMIN);
ret.getAccessTypes().add(HbaseAuthUtils.ACCESS_TYPE_EXECUTE);
return ret;
}
@Test
public void testPermissionList() throws Exception {
final TableName tableName = TableName.valueOf(name.getMethodName());
final byte[] family1 = Bytes.toBytes("f1");
final byte[] family2 = Bytes.toBytes("f2");
final byte[] qualifier = Bytes.toBytes("q");
// create table
Admin admin = TEST_UTIL.getAdmin();
if (admin.tableExists(tableName)) {
deleteTable(TEST_UTIL, tableName);
}
TableDescriptorBuilder.ModifyableTableDescriptor tableDescriptor =
new TableDescriptorBuilder.ModifyableTableDescriptor(tableName);
tableDescriptor.setColumnFamily(
new ColumnFamilyDescriptorBuilder.ModifyableColumnFamilyDescriptor(family1));
tableDescriptor.setColumnFamily(
new ColumnFamilyDescriptorBuilder.ModifyableColumnFamilyDescriptor(family2));
tableDescriptor.setOwner(USER_OWNER);
createTable(TEST_UTIL, tableDescriptor);
try {
List<UserPermission> perms =
admin.getUserPermissions(GetUserPermissionsRequest.newBuilder(tableName).build());
UserPermission ownerperm = new UserPermission(USER_OWNER.getName(),
Permission.newBuilder(tableName).withActions(Action.values()).build());
assertTrue("Owner should have all permissions on table",
hasFoundUserPermission(ownerperm, perms));
User user = User.createUserForTesting(TEST_UTIL.getConfiguration(), "user", new String[0]);
String userName = user.getShortName();
UserPermission up =
new UserPermission(userName, Permission.newBuilder(tableName).withFamily(family1)
.withQualifier(qualifier).withActions(Permission.Action.READ).build());
assertFalse("User should not be granted permission: " + up.toString(),
hasFoundUserPermission(up, perms));
// grant read permission
grantOnTable(TEST_UTIL, user.getShortName(), tableName, family1, qualifier,
Permission.Action.READ);
perms = admin.getUserPermissions(GetUserPermissionsRequest.newBuilder(tableName).build());
UserPermission upToVerify =
new UserPermission(userName, Permission.newBuilder(tableName).withFamily(family1)
.withQualifier(qualifier).withActions(Permission.Action.READ).build());
assertTrue("User should be granted permission: " + upToVerify.toString(),
hasFoundUserPermission(upToVerify, perms));
upToVerify = new UserPermission(userName, Permission.newBuilder(tableName).withFamily(family1)
.withQualifier(qualifier).withActions(Permission.Action.WRITE).build());
assertFalse("User should not be granted permission: " + upToVerify.toString(),
hasFoundUserPermission(upToVerify, perms));
// grant read+write
grantOnTable(TEST_UTIL, user.getShortName(), tableName, family1, qualifier,
Permission.Action.WRITE, Permission.Action.READ);
perms = admin.getUserPermissions(GetUserPermissionsRequest.newBuilder(tableName).build());
upToVerify = new UserPermission(userName,
Permission.newBuilder(tableName).withFamily(family1).withQualifier(qualifier)
.withActions(Permission.Action.WRITE, Permission.Action.READ).build());
assertTrue("User should be granted permission: " + upToVerify.toString(),
hasFoundUserPermission(upToVerify, perms));
// revoke
revokeFromTable(TEST_UTIL, user.getShortName(), tableName, family1, qualifier,
Permission.Action.WRITE, Permission.Action.READ);
perms = admin.getUserPermissions(GetUserPermissionsRequest.newBuilder(tableName).build());
assertFalse("User should not be granted permission: " + upToVerify.toString(),
hasFoundUserPermission(upToVerify, perms));
// disable table before modification
admin.disableTable(tableName);
User newOwner = User.createUserForTesting(conf, "new_owner", new String[] {});
tableDescriptor.setOwner(newOwner);
admin.modifyTable(tableDescriptor);
perms = admin.getUserPermissions(GetUserPermissionsRequest.newBuilder(tableName).build());
UserPermission newOwnerperm = new UserPermission(newOwner.getName(),
Permission.newBuilder(tableName).withActions(Action.values()).build());
assertTrue("New owner should have all permissions on table",
hasFoundUserPermission(newOwnerperm, perms));
} finally {
// delete table
deleteTable(TEST_UTIL, tableName);
}
}