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

The following examples show how to use org.apache.hadoop.hbase.security.access.AccessControlClient. 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
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 2
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 Project: phoenix   Source File: PhoenixAccessController.java    License: Apache License 2.0 5 votes vote down vote up
private void grantPermissions(final String toUser, final byte[] table, final Action... actions) throws IOException {
    User.runAsLoginUser(new PrivilegedExceptionAction<Void>() {
        @Override
        public Void run() throws Exception {
            try (Connection conn = ConnectionFactory.createConnection(env.getConfiguration())) {
                AccessControlClient.grant(conn, TableName.valueOf(table), toUser , null, null,
                        actions);
            } catch (Throwable e) {
                new DoNotRetryIOException(e);
            }
            return null;
        }
    });
}
 
Example 4
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 5
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 6
Source Project: phoenix   Source File: BasePermissionsIT.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void start(CoprocessorEnvironment env) throws IOException {
    super.start(env);
    configuration = env.getConfiguration();
    if(env instanceof RegionCoprocessorEnvironment) {
        aclRegion = AccessControlClient.ACL_TABLE_NAME.
                equals(((RegionCoprocessorEnvironment) env).getRegion().
                        getTableDescriptor().getTableName());
    }
}
 
Example 7
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 8
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
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 10
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 Project: hbase   Source File: TestSecureRESTServer.java    License: Apache License 2.0 4 votes vote down vote up
@Test
public void testPositiveAuthorization() throws Exception {
  // Create a table, write a row to it, grant read perms to the client
  UserGroupInformation superuser = UserGroupInformation.loginUserFromKeytabAndReturnUGI(
      SERVICE_PRINCIPAL, serviceKeytab.getAbsolutePath());
  final TableName table = TableName.valueOf("publicTable");
  superuser.doAs(new PrivilegedExceptionAction<Void>() {
    @Override
    public Void run() throws Exception {
      try (Connection conn = ConnectionFactory.createConnection(TEST_UTIL.getConfiguration())) {
        TableDescriptor desc = TableDescriptorBuilder.newBuilder(table)
            .setColumnFamily(ColumnFamilyDescriptorBuilder.of("f1"))
            .build();
        conn.getAdmin().createTable(desc);
        try (Table t = conn.getTable(table)) {
          Put p = new Put(Bytes.toBytes("a"));
          p.addColumn(Bytes.toBytes("f1"), new byte[0], Bytes.toBytes("1"));
          t.put(p);
        }
        AccessControlClient.grant(conn, CLIENT_PRINCIPAL, Action.READ);
      } catch (Throwable e) {
        if (e instanceof Exception) {
          throw (Exception) e;
        } else {
          throw new Exception(e);
        }
      }
      return null;
    }
  });

  // Read that row as the client
  Pair<CloseableHttpClient,HttpClientContext> pair = getClient();
  CloseableHttpClient client = pair.getFirst();
  HttpClientContext context = pair.getSecond();

  HttpGet get = new HttpGet(new URL("http://localhost:"+ REST_TEST.getServletPort()).toURI()
      + "/" + table + "/a");
  get.addHeader("Accept", "application/json");
  UserGroupInformation user = UserGroupInformation.loginUserFromKeytabAndReturnUGI(
      CLIENT_PRINCIPAL, clientKeytab.getAbsolutePath());
  String jsonResponse = user.doAs(new PrivilegedExceptionAction<String>() {
    @Override
    public String run() throws Exception {
      try (CloseableHttpResponse response = client.execute(get, context)) {
        final int statusCode = response.getStatusLine().getStatusCode();
        assertEquals(response.getStatusLine().toString(), HttpURLConnection.HTTP_OK, statusCode);
        HttpEntity entity = response.getEntity();
        return EntityUtils.toString(entity);
      }
    }
  });
  ObjectMapper mapper = new JacksonJaxbJsonProvider()
      .locateMapper(CellSetModel.class, MediaType.APPLICATION_JSON_TYPE);
  CellSetModel model = mapper.readValue(jsonResponse, CellSetModel.class);
  assertEquals(1, model.getRows().size());
  RowModel row = model.getRows().get(0);
  assertEquals("a", Bytes.toString(row.getKey()));
  assertEquals(1, row.getCells().size());
  CellModel cell = row.getCells().get(0);
  assertEquals("1", Bytes.toString(cell.getValue()));
}
 
Example 12
Source Project: phoenix   Source File: BasePermissionsIT.java    License: Apache License 2.0 4 votes vote down vote up
void grantPermissions(String toUser, Set<String> tablesToGrant, Permission.Action... actions) throws Throwable {
    for (String table : tablesToGrant) {
        AccessControlClient.grant(getUtility().getConnection(), TableName.valueOf(table), toUser, null, null,
                actions);
    }
}
 
Example 13
Source Project: phoenix   Source File: BasePermissionsIT.java    License: Apache License 2.0 4 votes vote down vote up
void grantPermissions(String toUser, String namespace, Permission.Action... actions) throws Throwable {
    AccessControlClient.grant(getUtility().getConnection(), namespace, toUser, actions);
}
 
Example 14
Source Project: phoenix   Source File: BasePermissionsIT.java    License: Apache License 2.0 4 votes vote down vote up
void grantPermissions(String groupEntry, Permission.Action... actions) throws IOException, Throwable {
    AccessControlClient.grant(getUtility().getConnection(), groupEntry, actions);
}
 
Example 15
Source Project: phoenix   Source File: BasePermissionsIT.java    License: Apache License 2.0 4 votes vote down vote up
void revokeAll() throws Throwable {
    AccessControlClient.revoke(getUtility().getConnection(), AuthUtil.toGroupEntry(GROUP_SYSTEM_ACCESS), Permission.Action.values() );
    AccessControlClient.revoke(getUtility().getConnection(), regularUser1.getShortName(), Permission.Action.values() );
    AccessControlClient.revoke(getUtility().getConnection(), unprivilegedUser.getShortName(), Permission.Action.values() );
}
 
Example 16
Source Project: phoenix   Source File: BasePermissionsIT.java    License: 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();
    }
}