org.apache.hadoop.hbase.security.User Java Examples

The following examples show how to use org.apache.hadoop.hbase.security.User. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AuthManager.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #2
Source File: TestCellACLWithMultipleVersions.java    From hbase with Apache License 2.0 6 votes vote down vote up
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;
    }
  });
}
 
Example #3
Source File: PhoenixEmbeddedDriver.java    From phoenix with Apache License 2.0 6 votes vote down vote up
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");
    }
}
 
Example #4
Source File: AccessChecker.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
  }
}
 
Example #5
Source File: TestVisibilityLabelsWithSLGStack.java    From hbase with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #6
Source File: AccessController.java    From hbase with Apache License 2.0 6 votes vote down vote up
@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.");
}
 
Example #7
Source File: AccessController.java    From hbase with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #8
Source File: PhoenixAccessController.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
 * @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;
}
 
Example #9
Source File: TestAccessControlFilter.java    From hbase with Apache License 2.0 6 votes vote down vote up
@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]);
}
 
Example #10
Source File: TestSnapshotScannerHDFSAclController.java    From hbase with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #11
Source File: TestCellACLWithMultipleVersions.java    From hbase with Apache License 2.0 6 votes vote down vote up
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;
    }
  });
}
 
Example #12
Source File: ProcedureExecutor.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #13
Source File: SecureTestUtil.java    From hbase with Apache License 2.0 6 votes vote down vote up
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");
  }
}
 
Example #14
Source File: TestQuotaThrottle.java    From hbase with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #15
Source File: ThriftConnection.java    From hbase with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #16
Source File: AccessController.java    From hbase with Apache License 2.0 6 votes vote down vote up
@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;
    }
  });
}
 
Example #17
Source File: AccessChecker.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
  }
}
 
Example #18
Source File: StatisticsWriter.java    From phoenix with Apache License 2.0 6 votes vote down vote up
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;
        }
    });
}
 
Example #19
Source File: SecureTestUtil.java    From hbase with Apache License 2.0 6 votes vote down vote up
/** 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");
    }
  }
}
 
Example #20
Source File: PhoenixAccessController.java    From phoenix with Apache License 2.0 6 votes vote down vote up
/**
 * 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)))); }
}
 
Example #21
Source File: TestSnapshotScannerHDFSAclController.java    From hbase with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #22
Source File: StripeCompactor.java    From hbase with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #23
Source File: TestCellACLWithMultipleVersions.java    From hbase with Apache License 2.0 6 votes vote down vote up
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;
    }
  });
}
 
Example #24
Source File: TestQuotaAdmin.java    From hbase with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #25
Source File: TestQuotaAdmin.java    From hbase with Apache License 2.0 6 votes vote down vote up
@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));
}
 
Example #26
Source File: ConnectionCache.java    From hbase with Apache License 2.0 6 votes vote down vote up
/**
 * 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;
}
 
Example #27
Source File: AccessController.java    From hbase with Apache License 2.0 5 votes vote down vote up
/**
 * Verifies user has CREATE or ADMIN privileges on
 * the Column Families involved in the bulkLoadHFile
 * request. Specific Column Write privileges are presently
 * ignored.
 */
@Override
public void preBulkLoadHFile(ObserverContext<RegionCoprocessorEnvironment> ctx,
    List<Pair<byte[], String>> familyPaths) throws IOException {
  User user = getActiveUser(ctx);
  for(Pair<byte[],String> el : familyPaths) {
    accessChecker.requirePermission(user, "preBulkLoadHFile",
      ctx.getEnvironment().getRegion().getTableDescriptor().getTableName(), el.getFirst(), null,
      null, Action.ADMIN, Action.CREATE);
  }
}
 
Example #28
Source File: AccessController.java    From hbase with Apache License 2.0 5 votes vote down vote up
@Override
public boolean preCheckAndPut(final ObserverContext<RegionCoprocessorEnvironment> c,
    final byte [] row, final byte [] family, final byte [] qualifier,
    final CompareOperator op,
    final ByteArrayComparable comparator, final Put put,
    final boolean result) throws IOException {
  User user = getActiveUser(c);
  checkForReservedTagPresence(user, put);

  // Require READ and WRITE permissions on the table, CF, and KV to update
  RegionCoprocessorEnvironment env = c.getEnvironment();
  Map<byte[],? extends Collection<byte[]>> families = makeFamilyMap(family, qualifier);
  AuthResult authResult = permissionGranted(OpType.CHECK_AND_PUT,
      user, env, families, Action.READ, Action.WRITE);
  AccessChecker.logResult(authResult);
  if (!authResult.isAllowed()) {
    if (cellFeaturesEnabled && !compatibleEarlyTermination) {
      put.setAttribute(CHECK_COVERING_PERM, TRUE);
    } else if (authorizationEnabled) {
      throw new AccessDeniedException("Insufficient permissions " +
        authResult.toContextString());
    }
  }

  byte[] bytes = put.getAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL);
  if (bytes != null) {
    if (cellFeaturesEnabled) {
      addCellPermissions(bytes, put.getFamilyCellMap());
    } else {
      throw new DoNotRetryIOException("Cell ACLs cannot be persisted");
    }
  }
  return result;
}
 
Example #29
Source File: MasterCoprocessorHost.java    From hbase with Apache License 2.0 5 votes vote down vote up
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);
    }
  });
}
 
Example #30
Source File: GssSaslClientAuthenticationProvider.java    From hbase with Apache License 2.0 5 votes vote down vote up
@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;
}