类org.apache.hadoop.hbase.security.User源码实例Demo

下面列出了怎么用org.apache.hadoop.hbase.security.User的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: hbase   文件: AccessChecker.java
/**
 * Authorizes that the current user has any of the given permissions for the
 * given table, column family and column qualifier.
 *
 * @param user Active user to which authorization checks should be applied
 * @param request Request type
 * @param tableName Table requested
 * @param family    Column family param
 * @param qualifier Column qualifier param
 * @throws IOException           if obtaining the current user fails
 * @throws AccessDeniedException if user has no authorization
 */
public void requireTablePermission(User user, String request,
    TableName tableName,byte[] family, byte[] qualifier,
    Action... permissions) throws IOException {
  AuthResult result = null;

  for (Action permission : permissions) {
    if (authManager.authorizeUserTable(user, tableName, permission)) {
      result = AuthResult.allow(request, "Table permission granted",
          user, permission, tableName, null, null);
      result.getParams().setFamily(family).setQualifier(qualifier);
      break;
    } else {
      // rest of the world
      result = AuthResult.deny(request, "Insufficient permissions",
              user, permission, tableName, family, qualifier);
      result.getParams().setFamily(family).setQualifier(qualifier);
    }
  }
  logResult(result);
  if (!result.isAllowed()) {
    throw new AccessDeniedException("Insufficient permissions " + result.toContextString());
  }
}
 
源代码2 项目: hbase   文件: AccessController.java
@Override
public void postDeleteNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx,
    final String namespace) throws IOException {
  final Configuration conf = ctx.getEnvironment().getConfiguration();
  User.runAsLoginUser(new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      try (Table table =
          ctx.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) {
        PermissionStorage.removeNamespacePermissions(conf, namespace, table);
      }
      return null;
    }
  });
  zkPermissionWatcher.deleteNamespaceACLNode(namespace);
  LOG.info(namespace + " entry deleted in " + PermissionStorage.ACL_TABLE_NAME + " table.");
}
 
源代码3 项目: hbase   文件: TestVisibilityLabelsWithSLGStack.java
@BeforeClass
public static void setupBeforeClass() throws Exception {
  // setup configuration
  conf = TEST_UTIL.getConfiguration();
  VisibilityTestUtil.enableVisiblityLabels(conf);
  String classes = SimpleScanLabelGenerator.class.getCanonicalName() + " , "
      + LabelFilteringScanLabelGenerator.class.getCanonicalName();
  conf.setStrings(VisibilityUtils.VISIBILITY_LABEL_GENERATOR_CLASS, classes);
  conf.set("hbase.superuser", "admin");
  TEST_UTIL.startMiniCluster(1);
  SUPERUSER = User.createUserForTesting(conf, "admin", new String[] { "supergroup" });

  // Wait for the labels table to become available
  TEST_UTIL.waitTableEnabled(LABELS_TABLE_NAME.getName(), 50000);
  addLabels();
}
 
源代码4 项目: phoenix   文件: PhoenixEmbeddedDriver.java
public ConnectionInfo(String zookeeperQuorum, Integer port, String rootNode, String principal, String keytab) {
    this.zookeeperQuorum = zookeeperQuorum;
    this.port = port;
    this.rootNode = rootNode;
    this.isConnectionless = PhoenixRuntime.CONNECTIONLESS.equals(zookeeperQuorum);
    this.principal = principal;
    this.keytab = keytab;
    try {
        this.user = User.getCurrent();
    } catch (IOException e) {
        throw new RuntimeException("Couldn't get the current user!!");
    }
    if (null == this.user) {
        throw new RuntimeException("Acquired null user which should never happen");
    }
}
 
源代码5 项目: hbase   文件: TestCellACLWithMultipleVersions.java
private void verifyUserDeniedForIncrementMultipleVersions(final User user, final byte[] row,
    final byte[] q1) throws IOException, InterruptedException {
  user.runAs(new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      try (Connection connection = ConnectionFactory.createConnection(conf)) {
        try (Table t = connection.getTable(testTable.getTableName())) {
          Increment inc = new Increment(row);
          inc.setTimeRange(0, 127);
          inc.addColumn(TEST_FAMILY1, q1, 2L);
          t.increment(inc);
          fail(user.getShortName() + " cannot do the increment.");
        } catch (Exception e) {

        }
      }
      return null;
    }
  });
}
 
源代码6 项目: hbase   文件: AccessController.java
@Override
public Result preAppendAfterRowLock(final ObserverContext<RegionCoprocessorEnvironment> c,
    final Append append) throws IOException {
  if (append.getAttribute(CHECK_COVERING_PERM) != null) {
    // We had failure with table, cf and q perm checks and now giving a chance for cell
    // perm check
    TableName table = c.getEnvironment().getRegion().getRegionInfo().getTable();
    AuthResult authResult = null;
    User user = getActiveUser(c);
    if (checkCoveringPermission(user, OpType.APPEND, c.getEnvironment(), append.getRow(),
        append.getFamilyCellMap(), append.getTimeRange().getMax(), Action.WRITE)) {
      authResult = AuthResult.allow(OpType.APPEND.toString(),
          "Covering cell set", user, Action.WRITE, table, append.getFamilyCellMap());
    } else {
      authResult = AuthResult.deny(OpType.APPEND.toString(),
          "Covering cell set", user, Action.WRITE, table, append.getFamilyCellMap());
    }
    AccessChecker.logResult(authResult);
    if (authorizationEnabled && !authResult.isAllowed()) {
      throw new AccessDeniedException("Insufficient permissions " +
        authResult.toContextString());
    }
  }
  return null;
}
 
源代码7 项目: phoenix   文件: PhoenixAccessController.java
/**
 * @return true if current user is a super user (whether as user running process,
 * declared as individual superuser or member of supergroup), false otherwise.
 * @param user to check
 * @throws IllegalStateException if lists of superusers/super groups
 *   haven't been initialized properly
 */
public static boolean isSuperUser(User user) {
    if (superUsers == null) {
        throw new IllegalStateException("Super users/super groups lists"
            + " haven't been initialized properly.");
    }
    if (superUsers.contains(user.getShortName())) {
        return true;
    }

    for (String group : user.getGroupNames()) {
        if (superGroups.contains(group)) {
            return true;
        }
    }
    return false;
}
 
源代码8 项目: hbase   文件: TestAccessControlFilter.java
@BeforeClass
public static void setupBeforeClass() throws Exception {
  TEST_UTIL = new HBaseTestingUtility();
  Configuration conf = TEST_UTIL.getConfiguration();
  // Up the handlers; this test needs more than usual.
  conf.setInt(HConstants.REGION_SERVER_HIGH_PRIORITY_HANDLER_COUNT, 10);
  enableSecurity(conf);
  verifyConfiguration(conf);

  // We expect 0.98 scanning semantics
  conf.setBoolean(AccessControlConstants.CF_ATTRIBUTE_EARLY_OUT, false);

  TEST_UTIL.startMiniCluster();
  TEST_UTIL.waitTableEnabled(PermissionStorage.ACL_TABLE_NAME.getName(), 50000);

  READER = User.createUserForTesting(conf, "reader", new String[0]);
  LIMITED = User.createUserForTesting(conf, "limited", new String[0]);
  DENIED = User.createUserForTesting(conf, "denied", new String[0]);
}
 
@Test
public void testRevokeGlobal2() throws Exception {
  final String grantUserName = name.getMethodName();
  User grantUser = User.createUserForTesting(conf, grantUserName, new String[] {});

  String namespace = name.getMethodName();
  String snapshot1 = namespace + "s1";
  TableName table1 = TableName.valueOf(namespace, name.getMethodName());
  TestHDFSAclHelper.createTableAndPut(TEST_UTIL, table1);
  snapshotAndWait(snapshot1, table1);

  // grant G(R), grant N(R), grant T(R) -> revoke G(R)
  SecureTestUtil.grantGlobal(TEST_UTIL, grantUserName, READ);
  SecureTestUtil.grantOnNamespace(TEST_UTIL, grantUserName, namespace, READ);
  TestHDFSAclHelper.grantOnTable(TEST_UTIL, grantUserName, table1, READ);
  SecureTestUtil.revokeGlobal(TEST_UTIL, grantUserName, READ);
  // check scan snapshot
  TestHDFSAclHelper.canUserScanSnapshot(TEST_UTIL, grantUser, snapshot1, 6);
  assertFalse(hasUserGlobalHdfsAcl(aclTable, grantUserName));
  checkUserAclEntry(FS, helper.getGlobalRootPaths(), grantUserName, false, false);
  assertTrue(hasUserNamespaceHdfsAcl(aclTable, grantUserName, namespace));
  checkUserAclEntry(FS, helper.getNamespaceRootPaths(namespace), grantUserName, true, true);
  deleteTable(table1);
}
 
源代码10 项目: hbase   文件: TestCellACLWithMultipleVersions.java
private void verifyUserDeniedForCheckAndDelete(final User user, final byte[] row,
    final byte[] value) throws IOException, InterruptedException {
  user.runAs(new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      try (Connection connection = ConnectionFactory.createConnection(conf)) {
        try (Table t = connection.getTable(testTable.getTableName())) {
          Delete d = new Delete(row);
          d.addColumns(TEST_FAMILY1, TEST_Q1);
          t.checkAndMutate(row, TEST_FAMILY1).qualifier(TEST_Q1).ifEquals(value).thenDelete(d);
          fail(user.getShortName() + " should not be allowed to do checkAndDelete");
        } catch (Exception e) {
        }
      }
      return null;
    }
  });
}
 
源代码11 项目: hbase   文件: ProcedureExecutor.java
/**
 * Check if the user is this procedure's owner
 * @param procId the target procedure
 * @param user the user
 * @return true if the user is the owner of the procedure,
 *   false otherwise or the owner is unknown.
 */
public boolean isProcedureOwner(long procId, User user) {
  if (user == null) {
    return false;
  }
  final Procedure<TEnvironment> runningProc = procedures.get(procId);
  if (runningProc != null) {
    return runningProc.getOwner().equals(user.getShortName());
  }

  final CompletedProcedureRetainer<TEnvironment> retainer = completed.get(procId);
  if (retainer != null) {
    return retainer.getProcedure().getOwner().equals(user.getShortName());
  }

  // Procedure either does not exist or has already completed and got cleaned up.
  // At this time, we cannot check the owner of the procedure
  return false;
}
 
源代码12 项目: hbase   文件: SecureTestUtil.java
public static void verifyConfiguration(Configuration conf) {
  String coprocs = conf.get(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY);
  boolean accessControllerLoaded = false;
  for (String coproc : coprocs.split(",")) {
    try {
      accessControllerLoaded = AccessController.class.isAssignableFrom(Class.forName(coproc));
      if (accessControllerLoaded) break;
    } catch (ClassNotFoundException cnfe) {
    }
  }
  if (!(conf.get(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY).contains(
      AccessController.class.getName())
      && accessControllerLoaded && conf.get(
      CoprocessorHost.REGIONSERVER_COPROCESSOR_CONF_KEY).contains(
      AccessController.class.getName()))) {
    throw new RuntimeException("AccessController is missing from a system coprocessor list");
  }
  if (conf.getInt(HFile.FORMAT_VERSION_KEY, 2) < HFile.MIN_FORMAT_VERSION_WITH_TAGS) {
    throw new RuntimeException("Post 0.96 security features require HFile version >= 3");
  }

  if (!conf.getBoolean(User.HBASE_SECURITY_AUTHORIZATION_CONF_KEY, false)) {
    throw new RuntimeException("Post 2.0.0 security features require set "
        + User.HBASE_SECURITY_AUTHORIZATION_CONF_KEY + " to true");
  }
}
 
源代码13 项目: hbase   文件: ThriftConnection.java
public ThriftConnection(Configuration conf, ExecutorService pool, final User user)
    throws IOException {
  this.conf = conf;
  this.user = user;
  this.host = conf.get(Constants.HBASE_THRIFT_SERVER_NAME);
  this.port = conf.getInt(Constants.HBASE_THRIFT_SERVER_PORT, -1);
  Preconditions.checkArgument(port > 0);
  Preconditions.checkArgument(host != null);
  this.isFramed = conf.getBoolean(Constants.FRAMED_CONF_KEY, Constants.FRAMED_CONF_DEFAULT);
  this.isCompact = conf.getBoolean(Constants.COMPACT_CONF_KEY, Constants.COMPACT_CONF_DEFAULT);
  this.operationTimeout = conf.getInt(HConstants.HBASE_CLIENT_OPERATION_TIMEOUT,
      HConstants.DEFAULT_HBASE_CLIENT_OPERATION_TIMEOUT);
  this.connectTimeout = conf.getInt(SOCKET_TIMEOUT_CONNECT, DEFAULT_SOCKET_TIMEOUT_CONNECT);

  String className = conf.get(Constants.HBASE_THRIFT_CLIENT_BUIDLER_CLASS,
      DefaultThriftClientBuilder.class.getName());
  try {
    Class<?> clazz = Class.forName(className);
    Constructor<?> constructor = clazz
        .getDeclaredConstructor(ThriftConnection.class);
    constructor.setAccessible(true);
    clientBuilder = (ThriftClientBuilder) constructor.newInstance(this);
  }catch (Exception e) {
    throw new IOException(e);
  }
}
 
源代码14 项目: hbase   文件: ConnectionCache.java
/**
 * Get the cached connection for the current user.
 * If none or timed out, create a new one.
 */
ConnectionInfo getCurrentConnection() throws IOException {
  String userName = getEffectiveUser();
  ConnectionInfo connInfo = connections.get(userName);
  if (connInfo == null || !connInfo.updateAccessTime()) {
    Lock lock = locker.acquireLock(userName);
    try {
      connInfo = connections.get(userName);
      if (connInfo == null) {
        UserGroupInformation ugi = realUser;
        if (!userName.equals(realUserName)) {
          ugi = UserGroupInformation.createProxyUser(userName, realUser);
        }
        User user = userProvider.create(ugi);
        Connection conn = ConnectionFactory.createConnection(conf, user);
        connInfo = new ConnectionInfo(conn, userName);
        connections.put(userName, connInfo);
      }
    } finally {
      lock.unlock();
    }
  }
  return connInfo;
}
 
源代码15 项目: hbase   文件: TestQuotaThrottle.java
@Test
public void testUserTableThrottle() throws Exception {
  final Admin admin = TEST_UTIL.getAdmin();
  final String userName = User.getCurrent().getShortName();

  // Add 6req/min limit
  admin.setQuota(QuotaSettingsFactory.throttleUser(userName, TABLE_NAMES[0],
    ThrottleType.REQUEST_NUMBER, 6, TimeUnit.MINUTES));
  triggerUserCacheRefresh(TEST_UTIL, false, TABLE_NAMES[0]);

  // should execute at max 6 requests on tables[0] and have no limit on tables[1]
  assertEquals(6, doPuts(100, FAMILY, QUALIFIER, tables[0]));
  assertEquals(30, doPuts(30, FAMILY, QUALIFIER, tables[1]));

  // wait a minute and you should get other 6 requests executed
  waitMinuteQuota();
  assertEquals(6, doPuts(100, FAMILY, QUALIFIER, tables[0]));

  // Remove all the limits
  admin.setQuota(QuotaSettingsFactory.unthrottleUser(userName, TABLE_NAMES[0]));
  triggerUserCacheRefresh(TEST_UTIL, true, TABLE_NAMES);
  assertEquals(60, doPuts(60, FAMILY, QUALIFIER, tables));
  assertEquals(60, doGets(60, tables));
}
 
源代码16 项目: hbase   文件: TestQuotaAdmin.java
@Test
public void testUserUnThrottleByType() throws Exception {
  final Admin admin = TEST_UTIL.getAdmin();
  final String userName = User.getCurrent().getShortName();
  String userName01 = "user01";
  // Add 6req/min limit
  admin.setQuota(QuotaSettingsFactory.throttleUser(userName, ThrottleType.REQUEST_NUMBER, 6,
    TimeUnit.MINUTES));
  admin.setQuota(
    QuotaSettingsFactory.throttleUser(userName, ThrottleType.REQUEST_SIZE, 6, TimeUnit.MINUTES));
  admin.setQuota(QuotaSettingsFactory.throttleUser(userName01, ThrottleType.REQUEST_NUMBER, 6,
    TimeUnit.MINUTES));
  admin.setQuota(QuotaSettingsFactory.throttleUser(userName01, ThrottleType.REQUEST_SIZE, 6,
    TimeUnit.MINUTES));
  admin.setQuota(
    QuotaSettingsFactory.unthrottleUserByThrottleType(userName, ThrottleType.REQUEST_NUMBER));
  assertEquals(3, getQuotaSettingCount(admin));
  admin.setQuota(
    QuotaSettingsFactory.unthrottleUserByThrottleType(userName, ThrottleType.REQUEST_SIZE));
  assertEquals(2, getQuotaSettingCount(admin));
  admin.setQuota(QuotaSettingsFactory.unthrottleUser(userName01));
  assertEquals(0, getQuotaSettingCount(admin));
}
 
源代码17 项目: hbase   文件: TestQuotaAdmin.java
@Test
public void testNameSpaceUnThrottleByType() throws Exception {
  final Admin admin = TEST_UTIL.getAdmin();
  final String userName = User.getCurrent().getShortName();
  // Add 6req/min limit
  admin.setQuota(QuotaSettingsFactory.throttleNamespace(NAMESPACES[0],
    ThrottleType.REQUEST_NUMBER, 6, TimeUnit.MINUTES));
  admin.setQuota(QuotaSettingsFactory.throttleNamespace(NAMESPACES[0], ThrottleType.REQUEST_SIZE,
    6, TimeUnit.MINUTES));
  admin.setQuota(QuotaSettingsFactory.throttleNamespace(NAMESPACES[1],
    ThrottleType.REQUEST_NUMBER, 6, TimeUnit.MINUTES));
  admin.setQuota(QuotaSettingsFactory.throttleNamespace(NAMESPACES[1], ThrottleType.REQUEST_SIZE,
    6, TimeUnit.MINUTES));
  admin.setQuota(QuotaSettingsFactory.unthrottleNamespaceByThrottleType(NAMESPACES[0],
    ThrottleType.REQUEST_NUMBER));
  assertEquals(3, getQuotaSettingCount(admin));
  admin.setQuota(QuotaSettingsFactory.unthrottleNamespaceByThrottleType(NAMESPACES[0],
    ThrottleType.REQUEST_SIZE));
  assertEquals(2, getQuotaSettingCount(admin));
  admin.setQuota(QuotaSettingsFactory.unthrottleNamespace(NAMESPACES[1]));
  assertEquals(0, getQuotaSettingCount(admin));
}
 
源代码18 项目: hbase   文件: TestCellACLWithMultipleVersions.java
private void verifyUserDeniedForDeleteExactVersion(final User user, final byte[] row,
    final byte[] q1, final byte[] q2) throws IOException, InterruptedException {
  user.runAs(new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      try (Connection connection = ConnectionFactory.createConnection(conf)) {
        try (Table t = connection.getTable(testTable.getTableName())) {
          Delete d = new Delete(row, 127);
          d.addColumns(TEST_FAMILY1, q1);
          d.addColumns(TEST_FAMILY1, q2);
          d.addFamily(TEST_FAMILY2, 129);
          t.delete(d);
          fail(user.getShortName() + " can not do the delete");
        } catch (Exception e) {

        }
      }
      return null;
    }
  });
}
 
源代码19 项目: hbase   文件: StripeCompactor.java
public List<Path> compact(CompactionRequestImpl request, final List<byte[]> targetBoundaries,
    final byte[] majorRangeFromRow, final byte[] majorRangeToRow,
    ThroughputController throughputController, User user) throws IOException {
  if (LOG.isDebugEnabled()) {
    StringBuilder sb = new StringBuilder();
    sb.append("Executing compaction with " + targetBoundaries.size() + " boundaries:");
    for (byte[] tb : targetBoundaries) {
      sb.append(" [").append(Bytes.toString(tb)).append("]");
    }
    LOG.debug(sb.toString());
  }
  return compact(request, new StripeInternalScannerFactory(majorRangeFromRow, majorRangeToRow),
    new CellSinkFactory<StripeMultiFileWriter>() {

      @Override
      public StripeMultiFileWriter createWriter(InternalScanner scanner, FileDetails fd,
          boolean shouldDropBehind) throws IOException {
        StripeMultiFileWriter writer = new StripeMultiFileWriter.BoundaryMultiWriter(
            store.getComparator(), targetBoundaries, majorRangeFromRow, majorRangeToRow);
        initMultiWriter(writer, scanner, fd, shouldDropBehind);
        return writer;
      }
    }, throughputController, user);
}
 
@Test
public void testRevokeGlobal1() throws Exception {
  final String grantUserName = name.getMethodName();
  User grantUser = User.createUserForTesting(conf, grantUserName, new String[] {});
  String namespace = name.getMethodName();
  TableName table1 = TableName.valueOf(namespace, name.getMethodName());
  String snapshot1 = namespace + "t1";

  TestHDFSAclHelper.createTableAndPut(TEST_UTIL, table1);
  snapshotAndWait(snapshot1, table1);
  SecureTestUtil.grantGlobal(TEST_UTIL, grantUserName, READ);
  SecureTestUtil.revokeGlobal(TEST_UTIL, grantUserName, READ);
  TestHDFSAclHelper.canUserScanSnapshot(TEST_UTIL, grantUser, snapshot1, -1);
  assertFalse(hasUserGlobalHdfsAcl(aclTable, grantUserName));
  checkUserAclEntry(FS, helper.getGlobalRootPaths(), grantUserName, false, false);
  deleteTable(table1);
}
 
源代码21 项目: phoenix   文件: PhoenixAccessController.java
/**
 * Authorizes that the current user has all the given permissions for the
 * given table and for the hbase namespace of the table
 * @param tableName Table requested
 * @throws IOException if obtaining the current user fails
 * @throws AccessDeniedException if user has no authorization
 */
private void requireAccess(String request, TableName tableName, Action... permissions) throws IOException {
    User user = getActiveUser();
    AuthResult result = null;
    List<Action> requiredAccess = new ArrayList<Action>();

    for (Action permission : permissions) {
         if (hasAccess(getUserPermissions(tableName), tableName, permission, user)) {
            result = AuthResult.allow(request, "Table permission granted", user, permission, tableName, null, null);
        } else {
            result = AuthResult.deny(request, "Insufficient permissions", user, permission, tableName, null, null);
            requiredAccess.add(permission);
        }
        logResult(result);
    }
    if (!requiredAccess.isEmpty()) {
        result = AuthResult.deny(request, "Insufficient permissions", user, requiredAccess.get(0), tableName, null,
                null);
    }
    if (!result.isAllowed()) { throw new AccessDeniedException("Insufficient permissions "
            + authString(user.getName(), tableName, new HashSet<Permission.Action>(Arrays.asList(permissions)))); }
}
 
源代码22 项目: hbase   文件: SecureTestUtil.java
/** This fails only in case of ADE or empty list for any of the actions. */
public static void verifyAllowed(User user, AccessTestAction... actions) throws Exception {
  for (AccessTestAction action : actions) {
    try {
      Object obj = user.runAs(action);
      if (obj != null && obj instanceof List<?>) {
        List<?> results = (List<?>) obj;
        if (results != null && results.isEmpty()) {
          fail("Empty non null results from action for user '" + user.getShortName() + "'");
        }
      }
    } catch (AccessDeniedException ade) {
      fail("Expected action to pass for user '" + user.getShortName() + "' but was denied");
    }
  }
}
 
源代码23 项目: phoenix   文件: StatisticsWriter.java
public void commitStats(final List<Mutation> mutations, final StatisticsCollector statsCollector)
        throws IOException {
    User.runAsLoginUser(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            commitLastStatsUpdatedTime(statsCollector);
            if (mutations.size() > 0) {
                byte[] row = mutations.get(0).getRow();
                MutateRowsRequest.Builder mrmBuilder = MutateRowsRequest.newBuilder();
                for (Mutation m : mutations) {
                    mrmBuilder.addMutationRequest(ProtobufUtil.toMutation(getMutationType(m), m));
                }
                MutateRowsRequest mrm = mrmBuilder.build();
                CoprocessorRpcChannel channel = statsWriterTable.coprocessorService(row);
                MultiRowMutationService.BlockingInterface service = MultiRowMutationService
                        .newBlockingStub(channel);
                try {
                    service.mutateRows(null, mrm);
                } catch (ServiceException ex) {
                    ProtobufUtil.toIOException(ex);
                }
            }
            return null;
        }
    });
}
 
源代码24 项目: hbase   文件: AccessChecker.java
/**
 * Checks that the user has the given global or namespace permission.
 * @param user Active user to which authorization checks should be applied
 * @param request Request type
 * @param namespace Name space as requested
 * @param filterUser User name to be filtered from permission as requested
 * @param permissions Actions being requested
 */
public void requireNamespacePermission(User user, String request, String namespace,
    String filterUser, Action... permissions) throws IOException {
  AuthResult result = null;

  for (Action permission : permissions) {
    if (authManager.authorizeUserNamespace(user, namespace, permission)) {
      result =
          AuthResult.allow(request, "Namespace permission granted", user, permission, namespace);
      break;
    } else {
      // rest of the world
      result = AuthResult.deny(request, "Insufficient permissions", user, permission, namespace);
    }
  }
  result.getParams().addExtraParam("filterUser", filterUser);
  logResult(result);
  if (!result.isAllowed()) {
    throw new AccessDeniedException("Insufficient permissions " + result.toContextString());
  }
}
 
源代码25 项目: hbase   文件: AccessController.java
@Override
public void postTruncateTable(ObserverContext<MasterCoprocessorEnvironment> ctx,
    final TableName tableName) throws IOException {
  final Configuration conf = ctx.getEnvironment().getConfiguration();
  User.runAsLoginUser(new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      List<UserPermission> perms = tableAcls.get(tableName);
      if (perms != null) {
        for (UserPermission perm : perms) {
          try (Table table =
              ctx.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) {
            PermissionStorage.addUserPermission(conf, perm, table);
          }
        }
      }
      tableAcls.remove(tableName);
      return null;
    }
  });
}
 
源代码26 项目: hbase   文件: AuthManager.java
/**
 * Check if user has given action privilige in table:family scope.
 * This method is for backward compatibility.
 * @param user user name
 * @param table table name
 * @param family family names
 * @param action one of action in [Read, Write, Create, Exec, Admin]
 * @return true if user has, false otherwise
 */
public boolean authorizeUserFamily(User user, TableName table,
    byte[] family, Permission.Action action) {
  PermissionCache<TablePermission> tblPermissions = tableCache.getOrDefault(table,
    TBL_NO_PERMISSION);
  if (authorizeFamily(tblPermissions.get(user.getShortName()), table, family, action)) {
    return true;
  }
  for (String group : user.getGroupNames()) {
    if (authorizeFamily(tblPermissions.get(AuthUtil.toGroupEntry(group)),
        table, family, action)) {
      return true;
    }
  }
  return false;
}
 
@Override
public UserGroupInformation getRealUser(User user) {
  final UserGroupInformation ugi = user.getUGI();
  // Unwrap the UGI with the real user when we're using Kerberos auth
  if (ugi != null && ugi.getRealUser() != null) {
    return ugi.getRealUser();
  }

  // Otherwise, use the UGI we were given
  return ugi;
}
 
源代码28 项目: hbase   文件: TestDefaultScanLabelGeneratorStack.java
@BeforeClass
public static void setupBeforeClass() throws Exception {
  // setup configuration
  conf = TEST_UTIL.getConfiguration();
  VisibilityTestUtil.enableVisiblityLabels(conf);
  // Not setting any SLG class. This means to use the default behavior.
  conf.set("hbase.superuser", "admin");
  TEST_UTIL.startMiniCluster(1);
  SUPERUSER = User.createUserForTesting(conf, "admin", new String[] { "supergroup" });
  TESTUSER = User.createUserForTesting(conf, "test", new String[] { });

  // Wait for the labels table to become available
  TEST_UTIL.waitTableEnabled(LABELS_TABLE_NAME.getName(), 50000);

  // Set up for the test
  SUPERUSER.runAs(new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      try (Connection conn = ConnectionFactory.createConnection(conf)) {
        VisibilityClient.addLabels(conn, new String[] { SECRET, CONFIDENTIAL });
        VisibilityClient.setAuths(conn, new String[] { CONFIDENTIAL }, TESTUSER.getShortName());
      } catch (Throwable t) {
        throw new IOException(t);
      }
      return null;
    }
  });
}
 
源代码29 项目: phoenix   文件: PhoenixAccessController.java
private User getActiveUser() throws IOException {
    Optional<User> user = RpcServer.getRequestUser();
    if (!user.isPresent()) {
        // for non-rpc handling, fallback to system user
        return userProvider.getCurrent();
    }
    return user.get();
}
 
源代码30 项目: hbase   文件: MasterCoprocessorHost.java
public void preEnableTableAction(final TableName tableName, final User user) throws IOException {
  execOperation(coprocEnvironments.isEmpty() ? null : new MasterObserverOperation(user) {
    @Override
    public void call(MasterObserver observer) throws IOException {
      observer.preEnableTableAction(this, tableName);
    }
  });
}
 
 类所在包
 同包方法