org.apache.hadoop.hbase.security.User#getShortName ( )源码实例Demo

下面列出了org.apache.hadoop.hbase.security.User#getShortName ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: atlas   文件: HBaseAtlasHook.java
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()");
    }
}
 
源代码2 项目: atlas   文件: HBaseAtlasHook.java
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()");
    }
}
 
源代码3 项目: hbase   文件: AccessChecker.java
/**
 * 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() + ")");
  }
}
 
源代码4 项目: hbase   文件: AccessChecker.java
/**
 * 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() + ")");
  }
}
 
源代码5 项目: spliceengine   文件: SIObserver.java
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());
}
 
源代码6 项目: ranger   文件: RangerAuthorizationCoprocessor.java
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.");
	}
}
 
源代码7 项目: ranger   文件: RangerAuthorizationCoprocessor.java
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!");
    }	
}
 
源代码8 项目: ranger   文件: RangerAuthorizationCoprocessor.java
@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;
}
 
源代码9 项目: ranger   文件: HbaseUserUtilsImpl.java
@Override
public String getUserAsString(User user) {
	if (user == null) {
		throw new IllegalArgumentException("User is null!");
	}
	else {
		return user.getShortName();
	}
}
 
源代码10 项目: hbase   文件: HFileReplicator.java
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);
}
 
源代码11 项目: hbase   文件: VisibilityController.java
@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;
}
 
源代码12 项目: hbase   文件: VisibilityController.java
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.");
    }
  }
}
 
源代码13 项目: hbase   文件: DefinedSetFilterScanLabelGenerator.java
@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;
}
 
源代码14 项目: hbase   文件: FeedUserAuthScanLabelGenerator.java
@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();
}
 
源代码15 项目: hbase   文件: EnforcingScanLabelGenerator.java
@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);
}
 
源代码16 项目: hbase   文件: AccessController.java
@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;
}
 
源代码17 项目: hbase   文件: AccessController.java
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.");
  }
}
 
源代码18 项目: phoenix   文件: BasePermissionsIT.java
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;
        }
    };
}
 
源代码19 项目: ranger   文件: RangerAuthorizationCoprocessor.java
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;
}
 
源代码20 项目: hbase   文件: TestAccessController.java
@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);
  }
}