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

The following examples show how to use org.apache.hadoop.hbase.security.access.Permission. 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: SIObserver.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #2
Source File: HBasePartitionAdmin.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
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 #3
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 #4
Source File: ChangePermsStatement.java    From phoenix with 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 File: IntegrationTestBigLinkedListWithVisibility.java    From hbase with Apache License 2.0 6 votes vote down vote up
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 #6
Source File: LoadTestDataGeneratorWithACL.java    From hbase with 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 #7
Source File: TestSecureExport.java    From hbase with 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 #8
Source File: HBasePartitionAdmin.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #9
Source File: Query.java    From hbase with 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 #10
Source File: HBasePartitionAdmin.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #11
Source File: TestVisibilityLabelsWithACL.java    From hbase with 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 #12
Source File: TestVisibilityLabelsWithACL.java    From hbase with 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 #13
Source File: TestVisibilityLabelsWithACL.java    From hbase with 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 #14
Source File: MasterCoprocessorHost.java    From hbase with 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 #15
Source File: SnapshotWithAclTestBase.java    From hbase with 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 #16
Source File: HBasePartitionAdmin.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #17
Source File: HBasePartitionAdmin.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
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 #18
Source File: BasePermissionsIT.java    From phoenix with 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 #19
Source File: PermissionNSEnabledIT.java    From phoenix with 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 #20
Source File: MasterCoprocessorHost.java    From hbase with 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 #21
Source File: CompatPermissionUtil.java    From phoenix with 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 #22
Source File: CompatPermissionUtil.java    From phoenix with 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 #23
Source File: TestGet.java    From hbase with 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 #24
Source File: Mutation.java    From hbase with 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 #25
Source File: RawAsyncHBaseAdmin.java    From hbase with 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 #26
Source File: PermissionNSEnabledIT.java    From phoenix with 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 #27
Source File: TestImmutableScan.java    From hbase with Apache License 2.0 4 votes vote down vote up
@Test
public void testScanCopyConstructor() throws Exception {
  Scan scan = new Scan();

  scan.addColumn(Bytes.toBytes("cf"), Bytes.toBytes("q"))
    .setACL("test_user2", new Permission(Permission.Action.READ))
    .setAllowPartialResults(true)
    .setAsyncPrefetch(false)
    .setAttribute("test_key", Bytes.toBytes("test_value"))
    .setAuthorizations(new Authorizations("test_label"))
    .setBatch(10)
    .setCacheBlocks(false)
    .setCaching(10)
    .setConsistency(Consistency.TIMELINE)
    .setFilter(new FilterList())
    .setId("scan_copy_constructor")
    .setIsolationLevel(IsolationLevel.READ_COMMITTED)
    .setLimit(100)
    .setLoadColumnFamiliesOnDemand(false)
    .setMaxResultSize(100)
    .setMaxResultsPerColumnFamily(1000)
    .readVersions(9999)
    .setMvccReadPoint(5)
    .setNeedCursorResult(true)
    .setPriority(1)
    .setRaw(true)
    .setReplicaId(3)
    .setReversed(true)
    .setRowOffsetPerColumnFamily(5)
    .setRowPrefixFilter(Bytes.toBytes("row_"))
    .setScanMetricsEnabled(true)
    .setSmall(true)
    .setReadType(Scan.ReadType.STREAM)
    .withStartRow(Bytes.toBytes("row_1"))
    .withStopRow(Bytes.toBytes("row_2"))
    .setTimeRange(0, 13);

  // create a copy of existing scan object
  Scan scanCopy = new ImmutableScan(scan);

  // validate fields of copied scan object match with the original scan object
  assertArrayEquals(scan.getACL(), scanCopy.getACL());
  assertEquals(scan.getAllowPartialResults(), scanCopy.getAllowPartialResults());
  assertArrayEquals(scan.getAttribute("test_key"), scanCopy.getAttribute("test_key"));
  assertEquals(scan.getAttributeSize(), scanCopy.getAttributeSize());
  assertEquals(scan.getAttributesMap(), scanCopy.getAttributesMap());
  assertEquals(scan.getAuthorizations().getLabels(), scanCopy.getAuthorizations().getLabels());
  assertEquals(scan.getBatch(), scanCopy.getBatch());
  assertEquals(scan.getCacheBlocks(), scanCopy.getCacheBlocks());
  assertEquals(scan.getCaching(), scanCopy.getCaching());
  assertEquals(scan.getConsistency(), scanCopy.getConsistency());
  assertEquals(scan.getFamilies().length, scanCopy.getFamilies().length);
  assertArrayEquals(scan.getFamilies()[0], scanCopy.getFamilies()[0]);
  assertEquals(scan.getFamilyMap(), scanCopy.getFamilyMap());
  assertEquals(scan.getFilter(), scanCopy.getFilter());
  assertEquals(scan.getId(), scanCopy.getId());
  assertEquals(scan.getIsolationLevel(), scanCopy.getIsolationLevel());
  assertEquals(scan.getLimit(), scanCopy.getLimit());
  assertEquals(scan.getLoadColumnFamiliesOnDemandValue(),
    scanCopy.getLoadColumnFamiliesOnDemandValue());
  assertEquals(scan.getMaxResultSize(), scanCopy.getMaxResultSize());
  assertEquals(scan.getMaxResultsPerColumnFamily(), scanCopy.getMaxResultsPerColumnFamily());
  assertEquals(scan.getMaxVersions(), scanCopy.getMaxVersions());
  assertEquals(scan.getMvccReadPoint(), scanCopy.getMvccReadPoint());
  assertEquals(scan.getPriority(), scanCopy.getPriority());
  assertEquals(scan.getReadType(), scanCopy.getReadType());
  assertEquals(scan.getReplicaId(), scanCopy.getReplicaId());
  assertEquals(scan.getRowOffsetPerColumnFamily(), scanCopy.getRowOffsetPerColumnFamily());
  assertArrayEquals(scan.getStartRow(), scanCopy.getStartRow());
  assertArrayEquals(scan.getStopRow(), scanCopy.getStopRow());
  assertEquals(scan.getTimeRange(), scanCopy.getTimeRange());
  assertEquals(scan.getFingerprint(), scanCopy.getFingerprint());
  assertEquals(scan.toMap(1), scanCopy.toMap(1));
  assertEquals(scan.toString(2), scanCopy.toString(2));
  assertEquals(scan.toJSON(2), scanCopy.toJSON(2));

  LOG.debug("Compare all getters of scan and scanCopy.");
  compareGetters(scan, scanCopy);

  testUnmodifiableSetters(scanCopy);
}
 
Example #28
Source File: BasePermissionsIT.java    From phoenix with Apache License 2.0 4 votes vote down vote up
@Test
public void testDeletingStatsShouldNotFailWithADEWhenTableDropped() throws Throwable {
    final String schema = "STATS_ENABLED";
    final String tableName = "DELETE_TABLE_IT";
    final String phoenixTableName = schema + "." + tableName;
    final String indexName1 = tableName + "_IDX1";
    final String lIndexName1 = tableName + "_LIDX1";
    final String viewName1 = schema+"."+tableName + "_V1";
    final String viewIndexName1 = tableName + "_VIDX1";
    grantSystemTableAccess();
    try {
        superUser1.runAs(new PrivilegedExceptionAction<Void>() {
            @Override
            public Void run() throws Exception {
                try {
                    verifyAllowed(createSchema(schema), superUser1);
                    //Neded Global ADMIN for flush operation during drop table
                    AccessControlClient.grant(getUtility().getConnection(),regularUser1.getName(), Permission.Action.ADMIN);
                    if (isNamespaceMapped) {
                        grantPermissions(regularUser1.getName(), schema, Permission.Action.CREATE);
                        grantPermissions(AuthUtil.toGroupEntry(GROUP_SYSTEM_ACCESS), schema, Permission.Action.CREATE);
                    } else {
                        grantPermissions(regularUser1.getName(),
                                NamespaceDescriptor.DEFAULT_NAMESPACE.getName(), Permission.Action.CREATE);
                        grantPermissions(AuthUtil.toGroupEntry(GROUP_SYSTEM_ACCESS),
                                NamespaceDescriptor.DEFAULT_NAMESPACE.getName(), Permission.Action.CREATE);
                    }
                } catch (Throwable e) {
                    if (e instanceof Exception) {
                        throw (Exception)e;
                    } else {
                        throw new Exception(e);
                    }
                }
                return null;
            }
        });

        verifyAllowed(createTable(phoenixTableName, 100), regularUser1);
        verifyAllowed(createIndex(indexName1,phoenixTableName),regularUser1);
        verifyAllowed(createLocalIndex(lIndexName1, phoenixTableName), regularUser1);
        verifyAllowed(createView(viewName1,phoenixTableName),regularUser1);
        verifyAllowed(createIndex(viewIndexName1, viewName1), regularUser1);
        verifyAllowed(updateStatsOnTable(phoenixTableName), regularUser1);
        Thread.sleep(10000);
        // Normal deletes should  fail when no write permissions given on stats table.
        verifyDenied(deleteDataFromStatsTable(), AccessDeniedException.class, regularUser1);
        verifyAllowed(dropIndex(viewIndexName1, viewName1), regularUser1);
        verifyAllowed(dropView(viewName1),regularUser1);
        verifyAllowed(dropIndex(indexName1, phoenixTableName), regularUser1);
        Thread.sleep(3000);
        verifyAllowed(readStatsAfterTableDelete(SchemaUtil.getPhysicalHBaseTableName(
                schema, indexName1, isNamespaceMapped).getString()), regularUser1);
        verifyAllowed(dropIndex(lIndexName1,  phoenixTableName), regularUser1);
        verifyAllowed(dropTable(phoenixTableName), regularUser1);
        Thread.sleep(3000);
        verifyAllowed(readStatsAfterTableDelete(SchemaUtil.getPhysicalHBaseTableName(
                schema, tableName, isNamespaceMapped).getString()), regularUser1);
    } finally {
        revokeAll();
    }
}
 
Example #29
Source File: CompatPermissionUtil.java    From phoenix with Apache License 2.0 4 votes vote down vote up
public static Permission getPermissionFromUP(UserPermission userPermission) {
    return userPermission;
}
 
Example #30
Source File: BasePermissionsIT.java    From phoenix with Apache License 2.0 4 votes vote down vote up
protected void grantSystemTableAccess() throws Exception{
    try (Connection conn = getConnection()) {
        if (isNamespaceMapped) {
            grantPermissions(regularUser1.getShortName(), PHOENIX_NAMESPACE_MAPPED_SYSTEM_TABLES, Permission.Action.READ,
                    Permission.Action.EXEC);
            grantPermissions(unprivilegedUser.getShortName(), PHOENIX_NAMESPACE_MAPPED_SYSTEM_TABLES,
                    Permission.Action.READ, Permission.Action.EXEC);
            grantPermissions(AuthUtil.toGroupEntry(GROUP_SYSTEM_ACCESS), PHOENIX_NAMESPACE_MAPPED_SYSTEM_TABLES,
                    Permission.Action.READ, Permission.Action.EXEC);
            // Local Index requires WRITE permission on SYSTEM.SEQUENCE TABLE.
            grantPermissions(regularUser1.getName(), Collections.singleton("SYSTEM:SEQUENCE"), Permission.Action.WRITE,
                    Permission.Action.READ, Permission.Action.EXEC);
            grantPermissions(unprivilegedUser.getName(), Collections.singleton("SYSTEM:SEQUENCE"), Permission.Action.WRITE,
                    Permission.Action.READ, Permission.Action.EXEC);
            grantPermissions(regularUser1.getShortName(), Collections.singleton("SYSTEM:MUTEX"), Permission.Action.WRITE,
                    Permission.Action.READ, Permission.Action.EXEC);
            grantPermissions(unprivilegedUser.getShortName(), Collections.singleton("SYSTEM:MUTEX"), Permission.Action.WRITE,
                    Permission.Action.READ, Permission.Action.EXEC);

        } else {
            grantPermissions(regularUser1.getName(), PHOENIX_SYSTEM_TABLES, Permission.Action.READ, Permission.Action.EXEC);
            grantPermissions(unprivilegedUser.getName(), PHOENIX_SYSTEM_TABLES, Permission.Action.READ, Permission.Action.EXEC);
            grantPermissions(AuthUtil.toGroupEntry(GROUP_SYSTEM_ACCESS), PHOENIX_SYSTEM_TABLES, Permission.Action.READ, Permission.Action.EXEC);
            // Local Index requires WRITE permission on SYSTEM.SEQUENCE TABLE.
            grantPermissions(regularUser1.getName(), Collections.singleton("SYSTEM.SEQUENCE"), Permission.Action.WRITE,
                    Permission.Action.READ, Permission.Action.EXEC);
            grantPermissions(unprivilegedUser.getName(), Collections.singleton("SYSTEM:SEQUENCE"), Permission.Action.WRITE,
                    Permission.Action.READ, Permission.Action.EXEC);
            grantPermissions(regularUser1.getShortName(), Collections.singleton("SYSTEM.MUTEX"), Permission.Action.WRITE,
                    Permission.Action.READ, Permission.Action.EXEC);
            grantPermissions(unprivilegedUser.getShortName(), Collections.singleton("SYSTEM.MUTEX"), Permission.Action.WRITE,
                    Permission.Action.READ, Permission.Action.EXEC);
        }
    } catch (Throwable e) {
        if (e instanceof Exception) {
            throw (Exception)e;
        } else {
            throw new Exception(e);
        }
    }
}