Java Code Examples for org.apache.hadoop.hbase.security.access.Permission

The following examples show how to use org.apache.hadoop.hbase.security.access.Permission. These examples are extracted from open source projects. 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 Project: hbase   Source File: TestSecureExport.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Sets the security firstly for getting the correct default realm.
 */
@BeforeClass
public static void beforeClass() throws Exception {
  UserProvider.setUserProviderForTesting(UTIL.getConfiguration(),
      HadoopSecurityEnabledUserProviderForTesting.class);
  setUpKdcServer();
  SecureTestUtil.enableSecurity(UTIL.getConfiguration());
  UTIL.getConfiguration().setBoolean(AccessControlConstants.EXEC_PERMISSION_CHECKS_KEY, true);
  VisibilityTestUtil.enableVisiblityLabels(UTIL.getConfiguration());
  SecureTestUtil.verifyConfiguration(UTIL.getConfiguration());
  setUpClusterKdc();
  UTIL.startMiniCluster();
  UTIL.waitUntilAllRegionsAssigned(PermissionStorage.ACL_TABLE_NAME);
  UTIL.waitUntilAllRegionsAssigned(VisibilityConstants.LABELS_TABLE_NAME);
  UTIL.waitTableEnabled(PermissionStorage.ACL_TABLE_NAME, 50000);
  UTIL.waitTableEnabled(VisibilityConstants.LABELS_TABLE_NAME, 50000);
  SecureTestUtil.grantGlobal(UTIL, USER_ADMIN,
          Permission.Action.ADMIN,
          Permission.Action.CREATE,
          Permission.Action.EXEC,
          Permission.Action.READ,
          Permission.Action.WRITE);
  addLabels(UTIL.getConfiguration(), Arrays.asList(USER_OWNER),
          Arrays.asList(PRIVATE, CONFIDENTIAL, SECRET, TOPSECRET));
}
 
Example 2
Source Project: hbase   Source File: LoadTestDataGeneratorWithACL.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public Mutation beforeMutate(long rowkeyBase, Mutation m) throws IOException {
  if (!(m instanceof Delete)) {
    if (userNames != null && userNames.length > 0) {
      int mod = ((int) rowkeyBase % this.userNames.length);
      if (((int) rowkeyBase % specialPermCellInsertionFactor) == 0) {
        // These cells cannot be read back when running as user userName[mod]
        if (LOG.isTraceEnabled()) {
          LOG.trace("Adding special perm " + rowkeyBase);
        }
        m.setACL(userNames[mod], new Permission(Permission.Action.WRITE));
      } else {
        m.setACL(userNames[mod], new Permission(Permission.Action.READ));
      }
    }
  }
  return m;
}
 
Example 3
private void createTable(Admin admin, TableName tableName, boolean setVersion,
    boolean acl) throws IOException {
  if (!admin.tableExists(tableName)) {
    TableDescriptorBuilder.ModifyableTableDescriptor tableDescriptor =
      new TableDescriptorBuilder.ModifyableTableDescriptor(tableName);
    ColumnFamilyDescriptorBuilder.ModifyableColumnFamilyDescriptor familyDescriptor =
      new ColumnFamilyDescriptorBuilder.ModifyableColumnFamilyDescriptor(FAMILY_NAME);
    if (setVersion) {
      familyDescriptor.setMaxVersions(DEFAULT_TABLES_COUNT);
    }
    tableDescriptor.setColumnFamily(familyDescriptor);
    admin.createTable(tableDescriptor);
    if (acl) {
      LOG.info("Granting permissions for user " + USER.getShortName());
      Permission.Action[] actions = { Permission.Action.READ };
      try {
        AccessControlClient.grant(ConnectionFactory.createConnection(getConf()), tableName,
            USER.getShortName(), null, null, actions);
      } catch (Throwable e) {
        LOG.error(HBaseMarkers.FATAL, "Error in granting permission for the user " +
            USER.getShortName(), e);
        throw new IOException(e);
      }
    }
  }
}
 
Example 4
Source Project: phoenix   Source File: ChangePermsStatement.java    License: Apache License 2.0 6 votes vote down vote up
public ChangePermsStatement(String permsString, boolean isSchemaName,
                            TableName tableName, String schemaName, boolean isGroupName, LiteralParseNode ugNode, boolean isGrantStatement) {
    // PHOENIX-672 HBase API doesn't allow to revoke specific permissions, hence this parameter will be ignored here.
    // To comply with SQL standards, we may support the user given permissions to revoke specific permissions in future.
    // GRANT permissions statement requires this parameter and the parsing will fail if it is not specified in SQL
    if(permsString != null) {
        Permission permission = new Permission(permsString.getBytes());
        permsList = permission.getActions();
    }
    if(isSchemaName) {
        this.schemaName = SchemaUtil.normalizeIdentifier(schemaName);
    } else {
        this.tableName = tableName;
    }
    name = SchemaUtil.normalizeLiteral(ugNode);
    name = isGroupName ? AuthUtil.toGroupEntry(name) : name;
    this.isGrantStatement = isGrantStatement;
}
 
Example 5
Source Project: phoenix   Source File: PhoenixAccessController.java    License: 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 6
private void grantPrivilegesIfNeeded(String userName, String spliceNamespace) throws Throwable {
    if (hasPrivileges(userName, spliceNamespace)) {
        LOG.info("User " + userName + " already has privileges on namespace " + spliceNamespace);
        return;
    }
    
    LOG.info("User " + userName + " lacks some privileges on namespace " + spliceNamespace + ", granting them");

    for (String user : Arrays.asList(userName, userName.toUpperCase(), userName.toLowerCase())) {
        AccessControlClient.grant(admin.getConnection(), spliceNamespace, user,
                Permission.Action.WRITE
                , Permission.Action.READ
                , Permission.Action.EXEC
        );
    }
}
 
Example 7
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());
}
 
Example 8
Source Project: hbase   Source File: MasterCoprocessorHost.java    License: Apache License 2.0 5 votes vote down vote up
public void preHasUserPermissions(String userName, List<Permission> permissions)
    throws IOException {
  execOperation(coprocEnvironments.isEmpty() ? null : new MasterObserverOperation() {
    @Override
    public void call(MasterObserver observer) throws IOException {
      observer.preHasUserPermissions(this, userName, permissions);
    }
  });
}
 
Example 9
Source Project: hbase   Source File: MasterCoprocessorHost.java    License: Apache License 2.0 5 votes vote down vote up
public void postHasUserPermissions(String userName, List<Permission> permissions)
    throws IOException {
  execOperation(coprocEnvironments.isEmpty() ? null : new MasterObserverOperation() {
    @Override
    public void call(MasterObserver observer) throws IOException {
      observer.postHasUserPermissions(this, userName, permissions);
    }
  });
}
 
Example 10
Source Project: hbase   Source File: TestVisibilityLabelsWithACL.java    License: Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setupBeforeClass() throws Exception {
  // setup configuration
  conf = TEST_UTIL.getConfiguration();
  SecureTestUtil.enableSecurity(conf);
  conf.set("hbase.coprocessor.master.classes", AccessController.class.getName() + ","
      + VisibilityController.class.getName());
  conf.set("hbase.coprocessor.region.classes", AccessController.class.getName() + ","
      + VisibilityController.class.getName());
  TEST_UTIL.startMiniCluster(2);

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

  // Create users for testing
  SUPERUSER = User.createUserForTesting(conf, "admin", new String[] { "supergroup" });
  NORMAL_USER1 = User.createUserForTesting(conf, "user1", new String[] {});
  NORMAL_USER2 = User.createUserForTesting(conf, "user2", new String[] {});
  // Grant users EXEC privilege on the labels table. For the purposes of this
  // test, we want to insure that access is denied even with the ability to access
  // the endpoint.
  SecureTestUtil.grantOnTable(TEST_UTIL, NORMAL_USER1.getShortName(), LABELS_TABLE_NAME,
    null, null, Permission.Action.EXEC);
  SecureTestUtil.grantOnTable(TEST_UTIL, NORMAL_USER2.getShortName(), LABELS_TABLE_NAME,
    null, null, Permission.Action.EXEC);
}
 
Example 11
Source Project: hbase   Source File: TestVisibilityLabelsWithACL.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testScanForUserWithFewerLabelAuthsThanLabelsInScanAuthorizations() throws Throwable {
  String[] auths = { SECRET };
  String user = "user2";
  VisibilityClient.setAuths(TEST_UTIL.getConnection(), auths, user);
  TableName tableName = TableName.valueOf(TEST_NAME.getMethodName());
  final Table table = createTableAndWriteDataWithLabels(tableName, SECRET + "&" + CONFIDENTIAL
      + "&!" + PRIVATE, SECRET + "&!" + PRIVATE);
  SecureTestUtil.grantOnTable(TEST_UTIL, NORMAL_USER2.getShortName(), tableName,
    null, null, Permission.Action.READ);
  PrivilegedExceptionAction<Void> scanAction = new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      Scan s = new Scan();
      s.setAuthorizations(new Authorizations(SECRET, CONFIDENTIAL));
      try (Connection connection = ConnectionFactory.createConnection(conf);
           Table t = connection.getTable(table.getName())) {
        ResultScanner scanner = t.getScanner(s);
        Result result = scanner.next();
        assertTrue(!result.isEmpty());
        assertTrue(Bytes.equals(Bytes.toBytes("row2"), result.getRow()));
        result = scanner.next();
        assertNull(result);
      }
      return null;
    }
  };
  NORMAL_USER2.runAs(scanAction);
}
 
Example 12
Source Project: hbase   Source File: TestVisibilityLabelsWithACL.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testVisibilityLabelsForUserWithNoAuths() throws Throwable {
  String user = "admin";
  String[] auths = { SECRET };
  try (Connection conn = ConnectionFactory.createConnection(conf)) {
    VisibilityClient.clearAuths(conn, auths, user); // Removing all auths if any.
    VisibilityClient.setAuths(conn, auths, "user1");
  }
  TableName tableName = TableName.valueOf(TEST_NAME.getMethodName());
  final Table table = createTableAndWriteDataWithLabels(tableName, SECRET);
  SecureTestUtil.grantOnTable(TEST_UTIL, NORMAL_USER1.getShortName(), tableName,
    null, null, Permission.Action.READ);
  SecureTestUtil.grantOnTable(TEST_UTIL, NORMAL_USER2.getShortName(), tableName,
    null, null, Permission.Action.READ);
  PrivilegedExceptionAction<Void> getAction = new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      Get g = new Get(row1);
      g.setAuthorizations(new Authorizations(SECRET, CONFIDENTIAL));
      try (Connection connection = ConnectionFactory.createConnection(conf);
           Table t = connection.getTable(table.getName())) {
        Result result = t.get(g);
        assertTrue(result.isEmpty());
      }
      return null;
    }
  };
  NORMAL_USER2.runAs(getAction);
}
 
Example 13
Source Project: hbase   Source File: SnapshotWithAclTestBase.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  TEST_UTIL.createTable(TableDescriptorBuilder.newBuilder(TEST_TABLE)
    .setColumnFamily(
      ColumnFamilyDescriptorBuilder.newBuilder(TEST_FAMILY).setMaxVersions(100).build())
    .setOwner(USER_OWNER).build(), new byte[][] { Bytes.toBytes("s") });
  TEST_UTIL.waitTableEnabled(TEST_TABLE);

  grantOnTable(TEST_UTIL, USER_RW.getShortName(), TEST_TABLE, TEST_FAMILY, null,
    Permission.Action.READ, Permission.Action.WRITE);

  grantOnTable(TEST_UTIL, USER_RO.getShortName(), TEST_TABLE, TEST_FAMILY, null,
    Permission.Action.READ);
}
 
Example 14
Source Project: hbase   Source File: Query.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param perms A map of permissions for a user or users
 */
public Query setACL(Map<String, Permission> perms) {
  ListMultimap<String, Permission> permMap = ArrayListMultimap.create();
  for (Map.Entry<String, Permission> entry : perms.entrySet()) {
    permMap.put(entry.getKey(), entry.getValue());
  }
  setAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL,
      AccessControlUtil.toUsersAndPermissions(permMap).toByteArray());
  return this;
}
 
Example 15
Source Project: hbase   Source File: Mutation.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param perms A map of permissions for a user or users
 */
public Mutation setACL(Map<String, Permission> perms) {
  ListMultimap<String, Permission> permMap = ArrayListMultimap.create();
  for (Map.Entry<String, Permission> entry : perms.entrySet()) {
    permMap.put(entry.getKey(), entry.getValue());
  }
  setAttribute(AccessControlConstants.OP_ATTRIBUTE_ACL,
    AccessControlUtil.toUsersAndPermissions(permMap).toByteArray());
  return this;
}
 
Example 16
Source Project: hbase   Source File: RawAsyncHBaseAdmin.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public CompletableFuture<List<Boolean>> hasUserPermissions(String userName,
    List<Permission> permissions) {
  return this.<List<Boolean>> newMasterCaller()
      .action((controller, stub) -> this
          .<HasUserPermissionsRequest, HasUserPermissionsResponse, List<Boolean>> call(controller,
            stub, ShadedAccessControlUtil.buildHasUserPermissionsRequest(userName, permissions),
            (s, c, req, done) -> s.hasUserPermissions(c, req, done),
            resp -> resp.getHasUserPermissionList()))
      .call();
}
 
Example 17
Source Project: hbase   Source File: TestGet.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void TestGetRowFromGetCopyConstructor() throws Exception {
  Get get = new Get(ROW);
  get.setFilter(null);
  get.setAuthorizations(new Authorizations("foo"));
  get.setACL("u", new Permission(Permission.Action.READ));
  get.setConsistency(Consistency.TIMELINE);
  get.setReplicaId(2);
  get.setIsolationLevel(IsolationLevel.READ_UNCOMMITTED);
  get.setCheckExistenceOnly(true);
  get.setTimeRange(3, 4);
  get.readVersions(11);
  get.setMaxResultsPerColumnFamily(10);
  get.setRowOffsetPerColumnFamily(11);
  get.setCacheBlocks(true);

  Get copyGet = new Get(get);
  assertEquals(0, Bytes.compareTo(get.getRow(), copyGet.getRow()));

  // from OperationWithAttributes
  assertEquals(get.getId(), copyGet.getId());

  // from Query class
  assertEquals(get.getFilter(), copyGet.getFilter());
  assertTrue(get.getAuthorizations().toString().equals(copyGet.getAuthorizations().toString()));
  assertTrue(Bytes.equals(get.getACL(), copyGet.getACL()));
  assertEquals(get.getConsistency(), copyGet.getConsistency());
  assertEquals(get.getReplicaId(), copyGet.getReplicaId());
  assertEquals(get.getIsolationLevel(), copyGet.getIsolationLevel());

  // from Get class
  assertEquals(get.isCheckExistenceOnly(), copyGet.isCheckExistenceOnly());
  assertTrue(get.getTimeRange().equals(copyGet.getTimeRange()));
  assertEquals(get.getMaxVersions(), copyGet.getMaxVersions());
  assertEquals(get.getMaxResultsPerColumnFamily(), copyGet.getMaxResultsPerColumnFamily());
  assertEquals(get.getRowOffsetPerColumnFamily(), copyGet.getRowOffsetPerColumnFamily());
  assertEquals(get.getCacheBlocks(), copyGet.getCacheBlocks());
  assertEquals(get.getId(), copyGet.getId());
}
 
Example 18
Source Project: phoenix   Source File: CompatPermissionUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean authorizeUserTable(AccessChecker accessChecker, User user, 
        TableName table, Permission.Action action) {
    if(accessChecker.getAuthManager().userHasAccess(user, table, action)) {
        return true;
    }
    String[] groupNames = user.getGroupNames();
    if (groupNames != null) {
      for (String group : groupNames) {
        if(accessChecker.getAuthManager().groupHasAccess(group, table, action)) {
            return true;
        }
      }
    }
    return false;
}
 
Example 19
Source Project: phoenix   Source File: CompatPermissionUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean authorizeUserTable(AccessChecker accessChecker, User user, 
        TableName table, Permission.Action action) {
    if(accessChecker.getAuthManager().userHasAccess(user, table, action)) {
        return true;
    }
    String[] groupNames = user.getGroupNames();
    if (groupNames != null) {
      for (String group : groupNames) {
        if(accessChecker.getAuthManager().groupHasAccess(group, table, action)) {
            return true;
        }
      }
    }
    return false;
}
 
Example 20
Source Project: phoenix   Source File: PermissionNSEnabledIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSchemaPermissions() throws Throwable{
    try {
        grantSystemTableAccess();
        final String schemaName = "S_" + generateUniqueName();
        superUser1.runAs(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                try {
                    AccessControlClient.grant(getUtility().getConnection(), regularUser1.getShortName(),
                            Permission.Action.ADMIN);
                } catch (Throwable e) {
                    if (e instanceof Exception) {
                        throw (Exception)e;
                    } else {
                        throw new Exception(e);
                    }
                }
                return null;
            }
        });
        verifyAllowed(createSchema(schemaName), regularUser1);
        // Unprivileged user cannot drop a schema
        verifyDenied(dropSchema(schemaName), AccessDeniedException.class, unprivilegedUser);
        verifyDenied(createSchema(schemaName), AccessDeniedException.class, unprivilegedUser);

        verifyAllowed(dropSchema(schemaName), regularUser1);
    } finally {
        revokeAll();
    }
}
 
Example 21
Source Project: phoenix   Source File: PermissionNSEnabledIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testConnectionCreationFailsWhenNoExecPermsOnSystemCatalog() throws Throwable {
    try {
        grantSystemTableAccess();
        superUser1.runAs((PrivilegedExceptionAction<Object>) () -> {
            TableName systemCatalogTableName =
                    TableName.valueOf(SchemaUtil.getPhysicalHBaseTableName(
                            SYSTEM_SCHEMA_NAME, SYSTEM_CATALOG_TABLE, true).getString());
            try {
                // Revoke Exec permissions for SYSTEM CATALOG for the unprivileged user
                AccessControlClient.revoke(getUtility().getConnection(), systemCatalogTableName,
                        unprivilegedUser.getShortName(), null, null, Permission.Action.EXEC);
            } catch (Throwable t) {
                if (t instanceof Exception) {
                    throw (Exception)t;
                } else {
                    throw new Exception(t);
                }
            }
            return null;
        });
        unprivilegedUser.runAs((PrivilegedExceptionAction<Void>) () -> {
            try (Connection ignored = getConnection()) {
                // We expect this to throw a wrapped AccessDeniedException.
                fail("Should have failed with a wrapped AccessDeniedException");
            } catch (Throwable ex) {
                assertTrue("Should not get an incompatible jars exception",
                        ex instanceof SQLException && ((SQLException)ex).getErrorCode() !=
                                SQLExceptionCode.INCOMPATIBLE_CLIENT_SERVER_JAR.getErrorCode());
                assertTrue("Expected a wrapped AccessDeniedException",
                        ex.getCause() instanceof AccessDeniedException);
            }
            return null;
        });
    } finally {
        revokeAll();
    }
}
 
Example 22
Source Project: phoenix   Source File: BasePermissionsIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testUpsertIntoImmutableTable() throws Throwable {
    final String schema = generateUniqueName();
    final String tableName = generateUniqueName();
    final String phoenixTableName = schema + "." + tableName;
    grantSystemTableAccess();
    try {
        superUser1.runAs(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                try {
                    verifyAllowed(createSchema(schema), superUser1);
                    verifyAllowed(onlyCreateImmutableTable(phoenixTableName), superUser1);
                } catch (Throwable e) {
                    if (e instanceof Exception) {
                        throw (Exception) e;
                    } else {
                        throw new Exception(e);
                    }
                }
                return null;
            }
        });

        if (isNamespaceMapped) {
            grantPermissions(unprivilegedUser.getShortName(), schema, Permission.Action.WRITE,
                Permission.Action.READ, Permission.Action.EXEC);
        } else {
            grantPermissions(unprivilegedUser.getShortName(),
                NamespaceDescriptor.DEFAULT_NAMESPACE.getName(), Permission.Action.WRITE,
                Permission.Action.READ, Permission.Action.EXEC);
        }
        verifyAllowed(upsertRowsIntoTable(phoenixTableName), unprivilegedUser);
        verifyAllowed(readTable(phoenixTableName), unprivilegedUser);
    } finally {
        revokeAll();
    }
}
 
Example 23
private boolean grantCreatePrivilege(String tableName, String userName) throws Throwable{

        if (hasCreatePrivilege(tableName, userName)){
            SpliceLogUtils.info(LOG, "User %s already has create privilege for table %s. Ignore grant request.",
                    userName, tableName);
            return false;
        }

        SpliceLogUtils.info(LOG, "granting create privilege to user %s on table %s", userName, tableName);
        for (String user : Arrays.asList(userName, userName.toUpperCase(), userName.toLowerCase())) {
            AccessControlClient.grant(admin.getConnection(), TableName.valueOf(tableName), user,null, null,
                    Permission.Action.CREATE);
        }
        return true;
    }
 
Example 24
private boolean hasCreatePrivilege(String tableName, String userName) throws Throwable{
    List<UserPermission> permissions = AccessControlClient.getUserPermissions(admin.getConnection(), tableName);
    for (String user : Arrays.asList(userName, userName.toUpperCase(), userName.toLowerCase())) {
        UserPermission up = getPermission(permissions, user);
        if (up == null || !up.implies(TableName.valueOf(tableName), null, null, Permission.Action.CREATE))
            return false;
    }
    return true;
}
 
Example 25
private boolean revokeCreatePrivilege(String tableName, String userName) throws Throwable{

        if (!hasCreatePrivilege(tableName, userName)){
            SpliceLogUtils.info(LOG, "User %s does not have create privilege for table %s. Ignore revoke request.",
                    userName, tableName);
            return false;
        }

        SpliceLogUtils.info(LOG, "revoking create privilege on table %s from user %s", tableName, userName);
        for (String user : Arrays.asList(userName, userName.toUpperCase(), userName.toLowerCase())) {
            AccessControlClient.revoke(admin.getConnection(), TableName.valueOf(tableName), user,null, null,
                    Permission.Action.CREATE);
        }
        return true;
    }
 
Example 26
private boolean hasPrivileges(String userName, String spliceNamespace) throws Throwable {
    List<UserPermission> permissions = AccessControlClient.getUserPermissions(admin.getConnection(), "@"+spliceNamespace);
    for (String user : Arrays.asList(userName, userName.toUpperCase(), userName.toLowerCase())) {
        UserPermission up = getPermission(permissions, user);
        if (up == null)
            return false;
        
        for (Permission.Action action : Arrays.asList(Permission.Action.WRITE, Permission.Action.READ, Permission.Action.EXEC)) {
            if (!up.implies(spliceNamespace, action))
                return false;
        }
    }
    return true;
}
 
Example 27
Source Project: hbase   Source File: ThriftAdmin.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public List<Boolean> hasUserPermissions(String userName, List<Permission> permissions) {
  throw new NotImplementedException("hasUserPermissions not supported in ThriftAdmin");
}
 
Example 28
Source Project: hbase   Source File: MasterRpcServices.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public GetUserPermissionsResponse getUserPermissions(RpcController controller,
    GetUserPermissionsRequest request) throws ServiceException {
  try {
    master.checkInitialized();
    if (master.cpHost != null && hasAccessControlServiceCoprocessor(master.cpHost)) {
      final String userName = request.hasUserName() ? request.getUserName().toStringUtf8() : null;
      String namespace =
          request.hasNamespaceName() ? request.getNamespaceName().toStringUtf8() : null;
      TableName table =
          request.hasTableName() ? ProtobufUtil.toTableName(request.getTableName()) : null;
      byte[] cf = request.hasColumnFamily() ? request.getColumnFamily().toByteArray() : null;
      byte[] cq =
          request.hasColumnQualifier() ? request.getColumnQualifier().toByteArray() : null;
      Type permissionType = request.hasType() ? request.getType() : null;
      master.getMasterCoprocessorHost().preGetUserPermissions(userName, namespace, table, cf, cq);

      List<UserPermission> perms = null;
      if (permissionType == Type.Table) {
        boolean filter = (cf != null || userName != null) ? true : false;
        perms = PermissionStorage.getUserTablePermissions(master.getConfiguration(), table, cf,
          cq, userName, filter);
      } else if (permissionType == Type.Namespace) {
        perms = PermissionStorage.getUserNamespacePermissions(master.getConfiguration(),
          namespace, userName, userName != null ? true : false);
      } else {
        perms = PermissionStorage.getUserPermissions(master.getConfiguration(), null, null, null,
          userName, userName != null ? true : false);
        // Skip super users when filter user is specified
        if (userName == null) {
          // Adding superusers explicitly to the result set as PermissionStorage do not store
          // them. Also using acl as table name to be inline with the results of global admin and
          // will help in avoiding any leakage of information about being superusers.
          for (String user : Superusers.getSuperUsers()) {
            perms.add(new UserPermission(user,
                Permission.newBuilder().withActions(Action.values()).build()));
          }
        }
      }

      master.getMasterCoprocessorHost().postGetUserPermissions(userName, namespace, table, cf,
        cq);
      AccessControlProtos.GetUserPermissionsResponse response =
          ShadedAccessControlUtil.buildGetUserPermissionsResponse(perms);
      return response;
    } else {
      throw new DoNotRetryIOException(
          new UnsupportedOperationException(AccessController.class.getName() + " is not loaded"));
    }
  } catch (IOException ioe) {
    throw new ServiceException(ioe);
  }
}
 
Example 29
Source Project: hbase   Source File: MasterObserver.java    License: Apache License 2.0 4 votes vote down vote up
default void preHasUserPermissions(ObserverContext<MasterCoprocessorEnvironment> ctx,
    String userName, List<Permission> permissions) throws IOException {
}
 
Example 30
Source Project: hbase   Source File: RSRpcServices.java    License: Apache License 2.0 4 votes vote down vote up
protected void requirePermission(String request, Permission.Action perm) throws IOException {
  if (accessChecker != null) {
    accessChecker.requirePermission(RpcServer.getRequestUser().orElse(null), request, null, perm);
  }
}