001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *     http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018package org.apache.hadoop.hbase.security.access;
019
020import java.io.IOException;
021import java.util.ArrayList;
022import java.util.Arrays;
023import java.util.HashSet;
024import java.util.List;
025import java.util.Optional;
026import java.util.Set;
027import java.util.stream.Collectors;
028import org.apache.hadoop.fs.Path;
029import org.apache.hadoop.hbase.Cell;
030import org.apache.hadoop.hbase.CellUtil;
031import org.apache.hadoop.hbase.HBaseInterfaceAudience;
032import org.apache.hadoop.hbase.NamespaceDescriptor;
033import org.apache.hadoop.hbase.TableName;
034import org.apache.hadoop.hbase.TableNotFoundException;
035import org.apache.hadoop.hbase.client.Admin;
036import org.apache.hadoop.hbase.client.ColumnFamilyDescriptorBuilder;
037import org.apache.hadoop.hbase.client.Connection;
038import org.apache.hadoop.hbase.client.Delete;
039import org.apache.hadoop.hbase.client.Get;
040import org.apache.hadoop.hbase.client.Put;
041import org.apache.hadoop.hbase.client.RegionInfo;
042import org.apache.hadoop.hbase.client.Result;
043import org.apache.hadoop.hbase.client.ResultScanner;
044import org.apache.hadoop.hbase.client.Scan;
045import org.apache.hadoop.hbase.client.SnapshotDescription;
046import org.apache.hadoop.hbase.client.Table;
047import org.apache.hadoop.hbase.client.TableDescriptor;
048import org.apache.hadoop.hbase.client.TableDescriptorBuilder;
049import org.apache.hadoop.hbase.coprocessor.CoreCoprocessor;
050import org.apache.hadoop.hbase.coprocessor.HasMasterServices;
051import org.apache.hadoop.hbase.coprocessor.MasterCoprocessor;
052import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment;
053import org.apache.hadoop.hbase.coprocessor.MasterObserver;
054import org.apache.hadoop.hbase.coprocessor.ObserverContext;
055import org.apache.hadoop.hbase.coprocessor.ObserverRpcCallContext;
056import org.apache.hadoop.hbase.master.MasterServices;
057import org.apache.hadoop.hbase.security.User;
058import org.apache.hadoop.hbase.security.UserProvider;
059import org.apache.hadoop.hbase.security.access.SnapshotScannerHDFSAclHelper.PathHelper;
060import org.apache.hadoop.hbase.util.Bytes;
061import org.apache.hadoop.hbase.util.Pair;
062import org.apache.yetus.audience.InterfaceAudience;
063import org.slf4j.Logger;
064import org.slf4j.LoggerFactory;
065
066import org.apache.hbase.thirdparty.com.google.common.collect.Sets;
067
068/**
069 * Set HDFS ACLs to hFiles to make HBase granted users have permission to scan snapshot
070 * <p>
071 * To use this feature, please mask sure HDFS config:
072 * <ul>
073 * <li>dfs.namenode.acls.enabled = true</li>
074 * <li>fs.permissions.umask-mode = 027 (or smaller umask than 027)</li>
075 * </ul>
076 * </p>
077 * <p>
078 * The implementation of this feature is as followings:
079 * <ul>
080 * <li>For common directories such as 'data' and 'archive', set other permission to '--x' to make
081 * everyone have the permission to access the directory.</li>
082 * <li>For namespace or table directories such as 'data/ns/table', 'archive/ns/table' and
083 * '.hbase-snapshot/snapshotName', set user 'r-x' access acl and 'r-x' default acl when following
084 * operations happen:
085 * <ul>
086 * <li>grant user with global, namespace or table permission;</li>
087 * <li>revoke user from global, namespace or table;</li>
088 * <li>snapshot table;</li>
089 * <li>truncate table;</li>
090 * </ul>
091 * </li>
092 * <li>Note: Because snapshots are at table level, so this feature just considers users with global,
093 * namespace or table permissions, ignores users with table CF or cell permissions.</li>
094 * </ul>
095 * </p>
096 */
097@CoreCoprocessor
098@InterfaceAudience.LimitedPrivate(HBaseInterfaceAudience.CONFIG)
099public class SnapshotScannerHDFSAclController implements MasterCoprocessor, MasterObserver {
100  private static final Logger LOG = LoggerFactory.getLogger(SnapshotScannerHDFSAclController.class);
101
102  private SnapshotScannerHDFSAclHelper hdfsAclHelper = null;
103  private PathHelper pathHelper = null;
104  private MasterServices masterServices = null;
105  private volatile boolean initialized = false;
106  private volatile boolean aclTableInitialized = false;
107  /** Provider for mapping principal names to Users */
108  private UserProvider userProvider;
109
110  @Override
111  public Optional<MasterObserver> getMasterObserver() {
112    return Optional.of(this);
113  }
114
115  @Override
116  public void preMasterInitialization(ObserverContext<MasterCoprocessorEnvironment> c)
117    throws IOException {
118    if (
119      c.getEnvironment().getConfiguration()
120        .getBoolean(SnapshotScannerHDFSAclHelper.ACL_SYNC_TO_HDFS_ENABLE, false)
121    ) {
122      MasterCoprocessorEnvironment mEnv = c.getEnvironment();
123      if (!(mEnv instanceof HasMasterServices)) {
124        throw new IOException("Does not implement HMasterServices");
125      }
126      masterServices = ((HasMasterServices) mEnv).getMasterServices();
127      hdfsAclHelper = new SnapshotScannerHDFSAclHelper(masterServices.getConfiguration(),
128        masterServices.getConnection());
129      pathHelper = hdfsAclHelper.getPathHelper();
130      hdfsAclHelper.setCommonDirectoryPermission();
131      initialized = true;
132      userProvider = UserProvider.instantiate(c.getEnvironment().getConfiguration());
133    } else {
134      LOG.warn("Try to initialize the coprocessor SnapshotScannerHDFSAclController but failure "
135        + "because the config " + SnapshotScannerHDFSAclHelper.ACL_SYNC_TO_HDFS_ENABLE
136        + " is false.");
137    }
138  }
139
140  @Override
141  public void postStartMaster(ObserverContext<MasterCoprocessorEnvironment> c) throws IOException {
142    if (!initialized) {
143      return;
144    }
145    try (Admin admin = c.getEnvironment().getConnection().getAdmin()) {
146      if (admin.tableExists(PermissionStorage.ACL_TABLE_NAME)) {
147        // Check if acl table has 'm' CF, if not, add 'm' CF
148        TableDescriptor tableDescriptor = admin.getDescriptor(PermissionStorage.ACL_TABLE_NAME);
149        boolean containHdfsAclFamily = Arrays.stream(tableDescriptor.getColumnFamilies()).anyMatch(
150          family -> Bytes.equals(family.getName(), SnapshotScannerHDFSAclStorage.HDFS_ACL_FAMILY));
151        if (!containHdfsAclFamily) {
152          TableDescriptorBuilder builder = TableDescriptorBuilder.newBuilder(tableDescriptor)
153            .setColumnFamily(ColumnFamilyDescriptorBuilder
154              .newBuilder(SnapshotScannerHDFSAclStorage.HDFS_ACL_FAMILY).build());
155          admin.modifyTable(builder.build());
156        }
157        aclTableInitialized = true;
158      } else {
159        throw new TableNotFoundException(
160          "Table " + PermissionStorage.ACL_TABLE_NAME + " is not created yet. Please check if "
161            + getClass().getName() + " is configured after " + AccessController.class.getName());
162      }
163    }
164  }
165
166  @Override
167  public void preStopMaster(ObserverContext<MasterCoprocessorEnvironment> c) {
168    if (initialized) {
169      hdfsAclHelper.close();
170    }
171  }
172
173  @Override
174  public void postCompletedCreateTableAction(ObserverContext<MasterCoprocessorEnvironment> c,
175    TableDescriptor desc, RegionInfo[] regions) throws IOException {
176    if (needHandleTableHdfsAcl(desc, "createTable " + desc.getTableName())) {
177      TableName tableName = desc.getTableName();
178      // 1. Create table directories to make HDFS acls can be inherited
179      hdfsAclHelper.createTableDirectories(tableName);
180      // 2. Add table owner HDFS acls
181      String owner = getActiveUser(c).getShortName();
182      hdfsAclHelper.addTableAcl(tableName, Sets.newHashSet(owner), "create");
183      // 3. Record table owner permission is synced to HDFS in acl table
184      SnapshotScannerHDFSAclStorage.addUserTableHdfsAcl(c.getEnvironment().getConnection(), owner,
185        tableName);
186    }
187  }
188
189  @Override
190  public void postCreateNamespace(ObserverContext<MasterCoprocessorEnvironment> c,
191    NamespaceDescriptor ns) throws IOException {
192    if (checkInitialized("createNamespace " + ns.getName())) {
193      // Create namespace directories to make HDFS acls can be inherited
194      List<Path> paths = hdfsAclHelper.getNamespaceRootPaths(ns.getName());
195      for (Path path : paths) {
196        hdfsAclHelper.createDirIfNotExist(path);
197      }
198    }
199  }
200
201  @Override
202  public void postCompletedSnapshotAction(ObserverContext<MasterCoprocessorEnvironment> c,
203    SnapshotDescription snapshot, TableDescriptor tableDescriptor) throws IOException {
204    if (needHandleTableHdfsAcl(tableDescriptor, "snapshot " + snapshot.getName())) {
205      // Add HDFS acls of users with table read permission to snapshot files
206      hdfsAclHelper.snapshotAcl(snapshot);
207    }
208  }
209
210  @Override
211  public void postCompletedTruncateTableAction(ObserverContext<MasterCoprocessorEnvironment> c,
212    TableName tableName) throws IOException {
213    if (needHandleTableHdfsAcl(tableName, "truncateTable " + tableName)) {
214      // 1. create tmp table directories
215      hdfsAclHelper.createTableDirectories(tableName);
216      // 2. Since the table directories is recreated, so add HDFS acls again
217      Set<String> users = hdfsAclHelper.getUsersWithTableReadAction(tableName, false, false);
218      hdfsAclHelper.addTableAcl(tableName, users, "truncate");
219    }
220  }
221
222  @Override
223  public void postCompletedDeleteTableAction(ObserverContext<MasterCoprocessorEnvironment> ctx,
224    TableName tableName) throws IOException {
225    if (!tableName.isSystemTable() && checkInitialized("deleteTable " + tableName)) {
226      /*
227       * Remove table user access HDFS acl from namespace directory if the user has no permissions
228       * of global, ns of the table or other tables of the ns, eg: Bob has 'ns1:t1' read permission,
229       * when delete 'ns1:t1', if Bob has global read permission, '@ns1' read permission or
230       * 'ns1:other_tables' read permission, then skip remove Bob access acl in ns1Dirs, otherwise,
231       * remove Bob access acl.
232       */
233      try (Table aclTable =
234        ctx.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) {
235        Set<String> users = SnapshotScannerHDFSAclStorage.getTableUsers(aclTable, tableName);
236        if (users.size() > 0) {
237          // 1. Remove table archive directory default ACLs
238          hdfsAclHelper.removeTableDefaultAcl(tableName, users);
239          // 2. Delete table owner permission is synced to HDFS in acl table
240          SnapshotScannerHDFSAclStorage.deleteTableHdfsAcl(aclTable, tableName);
241          // 3. Remove namespace access acls
242          Set<String> removeUsers = filterUsersToRemoveNsAccessAcl(aclTable, tableName, users);
243          if (removeUsers.size() > 0) {
244            hdfsAclHelper.removeNamespaceAccessAcl(tableName, removeUsers, "delete");
245          }
246        }
247      }
248    }
249  }
250
251  @Override
252  public void postModifyTable(ObserverContext<MasterCoprocessorEnvironment> ctx,
253    TableName tableName, TableDescriptor oldDescriptor, TableDescriptor currentDescriptor)
254    throws IOException {
255    try (Table aclTable =
256      ctx.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) {
257      if (
258        needHandleTableHdfsAcl(currentDescriptor, "modifyTable " + tableName)
259          && !hdfsAclHelper.isAclSyncToHdfsEnabled(oldDescriptor)
260      ) {
261        // 1. Create table directories used for acl inherited
262        hdfsAclHelper.createTableDirectories(tableName);
263        // 2. Add table users HDFS acls
264        Set<String> tableUsers = hdfsAclHelper.getUsersWithTableReadAction(tableName, false, false);
265        Set<String> users =
266          hdfsAclHelper.getUsersWithNamespaceReadAction(tableName.getNamespaceAsString(), true);
267        users.addAll(tableUsers);
268        hdfsAclHelper.addTableAcl(tableName, users, "modify");
269        // 3. Record table user acls are synced to HDFS in acl table
270        SnapshotScannerHDFSAclStorage.addUserTableHdfsAcl(ctx.getEnvironment().getConnection(),
271          tableUsers, tableName);
272      } else if (
273        needHandleTableHdfsAcl(oldDescriptor, "modifyTable " + tableName)
274          && !hdfsAclHelper.isAclSyncToHdfsEnabled(currentDescriptor)
275      ) {
276        // 1. Remove empty table directories
277        List<Path> tableRootPaths = hdfsAclHelper.getTableRootPaths(tableName, false);
278        for (Path path : tableRootPaths) {
279          hdfsAclHelper.deleteEmptyDir(path);
280        }
281        // 2. Remove all table HDFS acls
282        Set<String> tableUsers = hdfsAclHelper.getUsersWithTableReadAction(tableName, false, false);
283        Set<String> users =
284          hdfsAclHelper.getUsersWithNamespaceReadAction(tableName.getNamespaceAsString(), true);
285        users.addAll(tableUsers);
286        hdfsAclHelper.removeTableAcl(tableName, users);
287        // 3. Remove namespace access HDFS acls for users who only own permission for this table
288        hdfsAclHelper.removeNamespaceAccessAcl(tableName,
289          filterUsersToRemoveNsAccessAcl(aclTable, tableName, tableUsers), "modify");
290        // 4. Record table user acl is not synced to HDFS
291        SnapshotScannerHDFSAclStorage.deleteUserTableHdfsAcl(ctx.getEnvironment().getConnection(),
292          tableUsers, tableName);
293      }
294    }
295  }
296
297  @Override
298  public void postDeleteNamespace(ObserverContext<MasterCoprocessorEnvironment> ctx,
299    String namespace) throws IOException {
300    if (checkInitialized("deleteNamespace " + namespace)) {
301      try (Table aclTable =
302        ctx.getEnvironment().getConnection().getTable(PermissionStorage.ACL_TABLE_NAME)) {
303        // 1. Delete namespace archive dir default ACLs
304        Set<String> users = SnapshotScannerHDFSAclStorage.getEntryUsers(aclTable,
305          PermissionStorage.toNamespaceEntry(Bytes.toBytes(namespace)));
306        hdfsAclHelper.removeNamespaceDefaultAcl(namespace, users);
307        // 2. Record namespace user acl is not synced to HDFS
308        SnapshotScannerHDFSAclStorage.deleteNamespaceHdfsAcl(ctx.getEnvironment().getConnection(),
309          namespace);
310        // 3. Delete tmp namespace directory
311        /**
312         * Delete namespace tmp directory because it's created by this coprocessor when namespace is
313         * created to make namespace default acl can be inherited by tables. The namespace data
314         * directory is deleted by DeleteNamespaceProcedure, the namespace archive directory is
315         * deleted by HFileCleaner.
316         */
317        hdfsAclHelper.deleteEmptyDir(pathHelper.getTmpNsDir(namespace));
318      }
319    }
320  }
321
322  @Override
323  public void postGrant(ObserverContext<MasterCoprocessorEnvironment> c,
324    UserPermission userPermission, boolean mergeExistingPermissions) throws IOException {
325    if (
326      !checkInitialized(
327        "grant " + userPermission + ", merge existing permissions " + mergeExistingPermissions)
328    ) {
329      return;
330    }
331    Connection conn = c.getEnvironment().getConnection();
332    try (Table aclTable = conn.getTable(PermissionStorage.ACL_TABLE_NAME)) {
333      String userName = userPermission.getUser();
334      switch (userPermission.getAccessScope()) {
335        case GLOBAL:
336          UserPermission perm = getUserGlobalPermission(conn, userName);
337          if (perm != null && hdfsAclHelper.containReadAction(perm)) {
338            if (!isHdfsAclSet(aclTable, userName)) {
339              // 1. Get namespaces and tables which global user acls are already synced
340              Pair<Set<String>, Set<TableName>> skipNamespaceAndTables =
341                SnapshotScannerHDFSAclStorage.getUserNamespaceAndTable(aclTable, userName);
342              Set<String> skipNamespaces = skipNamespaceAndTables.getFirst();
343              Set<TableName> skipTables = skipNamespaceAndTables.getSecond().stream()
344                .filter(t -> !skipNamespaces.contains(t.getNamespaceAsString()))
345                .collect(Collectors.toSet());
346              // 2. Add HDFS acl(skip namespaces and tables directories whose acl is set)
347              hdfsAclHelper.grantAcl(userPermission, skipNamespaces, skipTables);
348              // 3. Record global acl is sync to HDFS
349              SnapshotScannerHDFSAclStorage.addUserGlobalHdfsAcl(aclTable, userName);
350            }
351          } else {
352            // The merged user permission doesn't contain READ, so remove user global HDFS acls if
353            // it's set
354            removeUserGlobalHdfsAcl(aclTable, userName, userPermission);
355          }
356          break;
357        case NAMESPACE:
358          String namespace = ((NamespacePermission) userPermission.getPermission()).getNamespace();
359          UserPermission nsPerm = getUserNamespacePermission(conn, userName, namespace);
360          if (nsPerm != null && hdfsAclHelper.containReadAction(nsPerm)) {
361            if (!isHdfsAclSet(aclTable, userName, namespace)) {
362              // 1. Get tables which namespace user acls are already synced
363              Set<TableName> skipTables = SnapshotScannerHDFSAclStorage
364                .getUserNamespaceAndTable(aclTable, userName).getSecond();
365              // 2. Add HDFS acl(skip tables directories whose acl is set)
366              hdfsAclHelper.grantAcl(userPermission, new HashSet<>(0), skipTables);
367            }
368            // 3. Record namespace acl is synced to HDFS
369            SnapshotScannerHDFSAclStorage.addUserNamespaceHdfsAcl(aclTable, userName, namespace);
370          } else {
371            // The merged user permission doesn't contain READ, so remove user namespace HDFS acls
372            // if it's set
373            removeUserNamespaceHdfsAcl(aclTable, userName, namespace, userPermission);
374          }
375          break;
376        case TABLE:
377          TablePermission tablePerm = (TablePermission) userPermission.getPermission();
378          if (needHandleTableHdfsAcl(tablePerm)) {
379            TableName tableName = tablePerm.getTableName();
380            UserPermission tPerm = getUserTablePermission(conn, userName, tableName);
381            if (tPerm != null && hdfsAclHelper.containReadAction(tPerm)) {
382              if (!isHdfsAclSet(aclTable, userName, tableName)) {
383                // 1. create table dirs
384                hdfsAclHelper.createTableDirectories(tableName);
385                // 2. Add HDFS acl
386                hdfsAclHelper.grantAcl(userPermission, new HashSet<>(0), new HashSet<>(0));
387              }
388              // 2. Record table acl is synced to HDFS
389              SnapshotScannerHDFSAclStorage.addUserTableHdfsAcl(aclTable, userName, tableName);
390            } else {
391              // The merged user permission doesn't contain READ, so remove user table HDFS acls if
392              // it's set
393              removeUserTableHdfsAcl(aclTable, userName, tableName, userPermission);
394            }
395          }
396          break;
397        default:
398          throw new IllegalArgumentException(
399            "Illegal user permission scope " + userPermission.getAccessScope());
400      }
401    }
402  }
403
404  @Override
405  public void postRevoke(ObserverContext<MasterCoprocessorEnvironment> c,
406    UserPermission userPermission) throws IOException {
407    if (checkInitialized("revoke " + userPermission)) {
408      Connection conn = c.getEnvironment().getConnection();
409      try (Table aclTable = conn.getTable(PermissionStorage.ACL_TABLE_NAME)) {
410        String userName = userPermission.getUser();
411        switch (userPermission.getAccessScope()) {
412          case GLOBAL:
413            UserPermission userGlobalPerm = getUserGlobalPermission(conn, userName);
414            if (userGlobalPerm == null || !hdfsAclHelper.containReadAction(userGlobalPerm)) {
415              removeUserGlobalHdfsAcl(aclTable, userName, userPermission);
416            }
417            break;
418          case NAMESPACE:
419            NamespacePermission nsPerm = (NamespacePermission) userPermission.getPermission();
420            UserPermission userNsPerm =
421              getUserNamespacePermission(conn, userName, nsPerm.getNamespace());
422            if (userNsPerm == null || !hdfsAclHelper.containReadAction(userNsPerm)) {
423              removeUserNamespaceHdfsAcl(aclTable, userName, nsPerm.getNamespace(), userPermission);
424            }
425            break;
426          case TABLE:
427            TablePermission tPerm = (TablePermission) userPermission.getPermission();
428            if (needHandleTableHdfsAcl(tPerm)) {
429              TableName tableName = tPerm.getTableName();
430              UserPermission userTablePerm = getUserTablePermission(conn, userName, tableName);
431              if (userTablePerm == null || !hdfsAclHelper.containReadAction(userTablePerm)) {
432                removeUserTableHdfsAcl(aclTable, userName, tableName, userPermission);
433              }
434            }
435            break;
436          default:
437            throw new IllegalArgumentException(
438              "Illegal user permission scope " + userPermission.getAccessScope());
439        }
440      }
441    }
442  }
443
444  private void removeUserGlobalHdfsAcl(Table aclTable, String userName,
445    UserPermission userPermission) throws IOException {
446    if (SnapshotScannerHDFSAclStorage.hasUserGlobalHdfsAcl(aclTable, userName)) {
447      // 1. Get namespaces and tables which global user acls are already synced
448      Pair<Set<String>, Set<TableName>> namespaceAndTable =
449        SnapshotScannerHDFSAclStorage.getUserNamespaceAndTable(aclTable, userName);
450      Set<String> skipNamespaces = namespaceAndTable.getFirst();
451      Set<TableName> skipTables = namespaceAndTable.getSecond().stream()
452        .filter(t -> !skipNamespaces.contains(t.getNamespaceAsString()))
453        .collect(Collectors.toSet());
454      // 2. Remove user HDFS acls(skip namespaces and tables directories
455      // whose acl must be reversed)
456      hdfsAclHelper.revokeAcl(userPermission, skipNamespaces, skipTables);
457      // 3. Remove global user acl is synced to HDFS in acl table
458      SnapshotScannerHDFSAclStorage.deleteUserGlobalHdfsAcl(aclTable, userName);
459    }
460  }
461
462  private void removeUserNamespaceHdfsAcl(Table aclTable, String userName, String namespace,
463    UserPermission userPermission) throws IOException {
464    if (SnapshotScannerHDFSAclStorage.hasUserNamespaceHdfsAcl(aclTable, userName, namespace)) {
465      if (!SnapshotScannerHDFSAclStorage.hasUserGlobalHdfsAcl(aclTable, userName)) {
466        // 1. Get tables whose namespace user acls are already synced
467        Set<TableName> skipTables =
468          SnapshotScannerHDFSAclStorage.getUserNamespaceAndTable(aclTable, userName).getSecond();
469        // 2. Remove user HDFS acls(skip tables directories whose acl must be reversed)
470        hdfsAclHelper.revokeAcl(userPermission, new HashSet<>(), skipTables);
471      }
472      // 3. Remove namespace user acl is synced to HDFS in acl table
473      SnapshotScannerHDFSAclStorage.deleteUserNamespaceHdfsAcl(aclTable, userName, namespace);
474    }
475  }
476
477  private void removeUserTableHdfsAcl(Table aclTable, String userName, TableName tableName,
478    UserPermission userPermission) throws IOException {
479    if (SnapshotScannerHDFSAclStorage.hasUserTableHdfsAcl(aclTable, userName, tableName)) {
480      if (
481        !SnapshotScannerHDFSAclStorage.hasUserGlobalHdfsAcl(aclTable, userName)
482          && !SnapshotScannerHDFSAclStorage.hasUserNamespaceHdfsAcl(aclTable, userName,
483            tableName.getNamespaceAsString())
484      ) {
485        // 1. Remove table acls
486        hdfsAclHelper.revokeAcl(userPermission, new HashSet<>(0), new HashSet<>(0));
487      }
488      // 2. Remove table user acl is synced to HDFS in acl table
489      SnapshotScannerHDFSAclStorage.deleteUserTableHdfsAcl(aclTable, userName, tableName);
490    }
491  }
492
493  private UserPermission getUserGlobalPermission(Connection conn, String userName)
494    throws IOException {
495    List<UserPermission> permissions =
496      PermissionUtils.filter(PermissionStorage.getGlobalPermissions(conn), userName);
497    return permissions.size() > 0 ? permissions.get(0) : null;
498  }
499
500  private UserPermission getUserNamespacePermission(Connection conn, String userName,
501    String namespace) throws IOException {
502    List<UserPermission> permissions =
503      PermissionUtils.filter(PermissionStorage.getNamespacePermissions(conn, namespace), userName);
504    return permissions.size() > 0 ? permissions.get(0) : null;
505  }
506
507  private UserPermission getUserTablePermission(Connection conn, String userName,
508    TableName tableName) throws IOException {
509    List<UserPermission> permissions = PermissionUtils
510      .filter(PermissionStorage.getTablePermissions(conn, tableName), userName).stream()
511      .filter(userPermission -> hdfsAclHelper
512        .isNotFamilyOrQualifierPermission((TablePermission) userPermission.getPermission()))
513      .collect(Collectors.toList());
514    return permissions.size() > 0 ? permissions.get(0) : null;
515  }
516
517  private boolean isHdfsAclSet(Table aclTable, String userName) throws IOException {
518    return isHdfsAclSet(aclTable, userName, null, null);
519  }
520
521  private boolean isHdfsAclSet(Table aclTable, String userName, String namespace)
522    throws IOException {
523    return isHdfsAclSet(aclTable, userName, namespace, null);
524  }
525
526  private boolean isHdfsAclSet(Table aclTable, String userName, TableName tableName)
527    throws IOException {
528    return isHdfsAclSet(aclTable, userName, null, tableName);
529  }
530
531  /**
532   * Check if user global/namespace/table HDFS acls is already set
533   */
534  private boolean isHdfsAclSet(Table aclTable, String userName, String namespace,
535    TableName tableName) throws IOException {
536    boolean isSet = SnapshotScannerHDFSAclStorage.hasUserGlobalHdfsAcl(aclTable, userName);
537    if (namespace != null) {
538      isSet = isSet
539        || SnapshotScannerHDFSAclStorage.hasUserNamespaceHdfsAcl(aclTable, userName, namespace);
540    }
541    if (tableName != null) {
542      isSet = isSet
543        || SnapshotScannerHDFSAclStorage.hasUserNamespaceHdfsAcl(aclTable, userName,
544          tableName.getNamespaceAsString())
545        || SnapshotScannerHDFSAclStorage.hasUserTableHdfsAcl(aclTable, userName, tableName);
546    }
547    return isSet;
548  }
549
550  @InterfaceAudience.Private
551  boolean checkInitialized(String operation) {
552    if (initialized) {
553      if (aclTableInitialized) {
554        return true;
555      } else {
556        LOG.warn("Skip set HDFS acls because acl table is not initialized when {}", operation);
557      }
558    }
559    return false;
560  }
561
562  private boolean needHandleTableHdfsAcl(TablePermission tablePermission) throws IOException {
563    return needHandleTableHdfsAcl(tablePermission.getTableName(), "")
564      && hdfsAclHelper.isNotFamilyOrQualifierPermission(tablePermission);
565  }
566
567  private boolean needHandleTableHdfsAcl(TableName tableName, String operation) throws IOException {
568    return !tableName.isSystemTable() && checkInitialized(operation)
569      && hdfsAclHelper.isAclSyncToHdfsEnabled(masterServices.getTableDescriptors().get(tableName));
570  }
571
572  private boolean needHandleTableHdfsAcl(TableDescriptor tableDescriptor, String operation) {
573    TableName tableName = tableDescriptor.getTableName();
574    return !tableName.isSystemTable() && checkInitialized(operation)
575      && hdfsAclHelper.isAclSyncToHdfsEnabled(tableDescriptor);
576  }
577
578  private User getActiveUser(ObserverContext<?> ctx) throws IOException {
579    // for non-rpc handling, fallback to system user
580    Optional<User> optionalUser = ctx.getRpcCallContext().map(ObserverRpcCallContext::getUser);
581    if (optionalUser.isPresent()) {
582      return optionalUser.get();
583    }
584    return userProvider.getCurrent();
585  }
586
587  /**
588   * Remove table user access HDFS acl from namespace directory if the user has no permissions of
589   * global, ns of the table or other tables of the ns, eg: Bob has 'ns1:t1' read permission, when
590   * delete 'ns1:t1', if Bob has global read permission, '@ns1' read permission or
591   * 'ns1:other_tables' read permission, then skip remove Bob access acl in ns1Dirs, otherwise,
592   * remove Bob access acl.
593   * @param aclTable    acl table
594   * @param tableName   the name of the table
595   * @param tablesUsers table users set
596   * @return users whose access acl will be removed from the namespace of the table
597   * @throws IOException if an error occurred
598   */
599  private Set<String> filterUsersToRemoveNsAccessAcl(Table aclTable, TableName tableName,
600    Set<String> tablesUsers) throws IOException {
601    Set<String> removeUsers = new HashSet<>();
602    byte[] namespace = tableName.getNamespace();
603    for (String user : tablesUsers) {
604      List<byte[]> userEntries = SnapshotScannerHDFSAclStorage.getUserEntries(aclTable, user);
605      boolean remove = true;
606      for (byte[] entry : userEntries) {
607        if (
608          PermissionStorage.isGlobalEntry(entry)
609            || (PermissionStorage.isNamespaceEntry(entry)
610              && Bytes.equals(PermissionStorage.fromNamespaceEntry(entry), namespace))
611            || (PermissionStorage.isTableEntry(entry) && !Bytes.equals(tableName.getName(), entry)
612              && Bytes.equals(TableName.valueOf(entry).getNamespace(), namespace))
613        ) {
614          remove = false;
615          break;
616        }
617      }
618      if (remove) {
619        removeUsers.add(user);
620      }
621    }
622    return removeUsers;
623  }
624
625  static final class SnapshotScannerHDFSAclStorage {
626    /**
627     * Add a new CF in HBase acl table to record if the HBase read permission is synchronized to
628     * related hfiles. The record has two usages: 1. check if we need to remove HDFS acls for a
629     * grant without READ permission(eg: grant user table read permission and then grant user table
630     * write permission without merging the existing permissions, in this case, need to remove HDFS
631     * acls); 2. skip some HDFS acl sync because it may be already set(eg: grant user table read
632     * permission and then grant user ns read permission; grant user table read permission and then
633     * grant user table write permission with merging the existing permissions).
634     */
635    static final byte[] HDFS_ACL_FAMILY = Bytes.toBytes("m");
636    // The value 'R' has no specific meaning, if cell value is not null, it means that the user HDFS
637    // acls is set to hfiles.
638    private static final byte[] HDFS_ACL_VALUE = Bytes.toBytes("R");
639
640    static void addUserGlobalHdfsAcl(Table aclTable, String user) throws IOException {
641      addUserEntry(aclTable, user, PermissionStorage.ACL_GLOBAL_NAME);
642    }
643
644    static void addUserNamespaceHdfsAcl(Table aclTable, String user, String namespace)
645      throws IOException {
646      addUserEntry(aclTable, user, PermissionStorage.toNamespaceEntry(namespace));
647    }
648
649    static void addUserTableHdfsAcl(Connection connection, Set<String> users, TableName tableName)
650      throws IOException {
651      try (Table aclTable = connection.getTable(PermissionStorage.ACL_TABLE_NAME)) {
652        for (String user : users) {
653          addUserTableHdfsAcl(aclTable, user, tableName);
654        }
655      }
656    }
657
658    static void addUserTableHdfsAcl(Connection connection, String user, TableName tableName)
659      throws IOException {
660      try (Table aclTable = connection.getTable(PermissionStorage.ACL_TABLE_NAME)) {
661        addUserTableHdfsAcl(aclTable, user, tableName);
662      }
663    }
664
665    static void addUserTableHdfsAcl(Table aclTable, String user, TableName tableName)
666      throws IOException {
667      addUserEntry(aclTable, user, tableName.getName());
668    }
669
670    private static void addUserEntry(Table t, String user, byte[] entry) throws IOException {
671      Put p = new Put(entry);
672      p.addColumn(HDFS_ACL_FAMILY, Bytes.toBytes(user), HDFS_ACL_VALUE);
673      t.put(p);
674    }
675
676    static void deleteUserGlobalHdfsAcl(Table aclTable, String user) throws IOException {
677      deleteUserEntry(aclTable, user, PermissionStorage.ACL_GLOBAL_NAME);
678    }
679
680    static void deleteUserNamespaceHdfsAcl(Table aclTable, String user, String namespace)
681      throws IOException {
682      deleteUserEntry(aclTable, user, PermissionStorage.toNamespaceEntry(namespace));
683    }
684
685    static void deleteUserTableHdfsAcl(Table aclTable, String user, TableName tableName)
686      throws IOException {
687      deleteUserEntry(aclTable, user, tableName.getName());
688    }
689
690    static void deleteUserTableHdfsAcl(Connection connection, Set<String> users,
691      TableName tableName) throws IOException {
692      try (Table aclTable = connection.getTable(PermissionStorage.ACL_TABLE_NAME)) {
693        for (String user : users) {
694          deleteUserTableHdfsAcl(aclTable, user, tableName);
695        }
696      }
697    }
698
699    private static void deleteUserEntry(Table aclTable, String user, byte[] entry)
700      throws IOException {
701      Delete delete = new Delete(entry);
702      delete.addColumns(HDFS_ACL_FAMILY, Bytes.toBytes(user));
703      aclTable.delete(delete);
704    }
705
706    static void deleteNamespaceHdfsAcl(Connection connection, String namespace) throws IOException {
707      try (Table aclTable = connection.getTable(PermissionStorage.ACL_TABLE_NAME)) {
708        deleteEntry(aclTable, PermissionStorage.toNamespaceEntry(namespace));
709      }
710    }
711
712    static void deleteTableHdfsAcl(Table aclTable, TableName tableName) throws IOException {
713      deleteEntry(aclTable, tableName.getName());
714    }
715
716    private static void deleteEntry(Table aclTable, byte[] entry) throws IOException {
717      Delete delete = new Delete(entry);
718      delete.addFamily(HDFS_ACL_FAMILY);
719      aclTable.delete(delete);
720    }
721
722    static Set<String> getTableUsers(Table aclTable, TableName tableName) throws IOException {
723      return getEntryUsers(aclTable, tableName.getName());
724    }
725
726    private static Set<String> getEntryUsers(Table aclTable, byte[] entry) throws IOException {
727      Set<String> users = new HashSet<>();
728      Get get = new Get(entry);
729      get.addFamily(HDFS_ACL_FAMILY);
730      Result result = aclTable.get(get);
731      List<Cell> cells = result.listCells();
732      if (cells != null) {
733        for (Cell cell : cells) {
734          if (cell != null) {
735            users.add(Bytes.toString(CellUtil.cloneQualifier(cell)));
736          }
737        }
738      }
739      return users;
740    }
741
742    static Pair<Set<String>, Set<TableName>> getUserNamespaceAndTable(Table aclTable,
743      String userName) throws IOException {
744      Set<String> namespaces = new HashSet<>();
745      Set<TableName> tables = new HashSet<>();
746      List<byte[]> userEntries = getUserEntries(aclTable, userName);
747      for (byte[] entry : userEntries) {
748        if (PermissionStorage.isNamespaceEntry(entry)) {
749          namespaces.add(Bytes.toString(PermissionStorage.fromNamespaceEntry(entry)));
750        } else if (PermissionStorage.isTableEntry(entry)) {
751          tables.add(TableName.valueOf(entry));
752        }
753      }
754      return new Pair<>(namespaces, tables);
755    }
756
757    static List<byte[]> getUserEntries(Table aclTable, String userName) throws IOException {
758      Scan scan = new Scan();
759      scan.addColumn(HDFS_ACL_FAMILY, Bytes.toBytes(userName));
760      ResultScanner scanner = aclTable.getScanner(scan);
761      List<byte[]> entry = new ArrayList<>();
762      for (Result result : scanner) {
763        if (result != null && result.getRow() != null) {
764          entry.add(result.getRow());
765        }
766      }
767      return entry;
768    }
769
770    static boolean hasUserGlobalHdfsAcl(Table aclTable, String user) throws IOException {
771      return hasUserEntry(aclTable, user, PermissionStorage.ACL_GLOBAL_NAME);
772    }
773
774    static boolean hasUserNamespaceHdfsAcl(Table aclTable, String user, String namespace)
775      throws IOException {
776      return hasUserEntry(aclTable, user, PermissionStorage.toNamespaceEntry(namespace));
777    }
778
779    static boolean hasUserTableHdfsAcl(Table aclTable, String user, TableName tableName)
780      throws IOException {
781      return hasUserEntry(aclTable, user, tableName.getName());
782    }
783
784    private static boolean hasUserEntry(Table aclTable, String userName, byte[] entry)
785      throws IOException {
786      Get get = new Get(entry);
787      get.addColumn(HDFS_ACL_FAMILY, Bytes.toBytes(userName));
788      return aclTable.exists(get);
789    }
790  }
791}