View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   * http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  package org.apache.hadoop.hbase.security.access;
20  
21  import static org.junit.Assert.assertEquals;
22  import static org.junit.Assert.fail;
23  
24  import java.io.IOException;
25  import java.lang.reflect.UndeclaredThrowableException;
26  import java.security.PrivilegedActionException;
27  import java.security.PrivilegedExceptionAction;
28  import java.util.List;
29  import java.util.Map;
30  import java.util.concurrent.Callable;
31  import java.util.concurrent.CountDownLatch;
32  
33  import org.apache.commons.logging.Log;
34  import org.apache.commons.logging.LogFactory;
35  import org.apache.hadoop.conf.Configuration;
36  import org.apache.hadoop.hbase.Coprocessor;
37  import org.apache.hadoop.hbase.HBaseTestingUtility;
38  import org.apache.hadoop.hbase.HConstants;
39  import org.apache.hadoop.hbase.HColumnDescriptor;
40  import org.apache.hadoop.hbase.HTableDescriptor;
41  import org.apache.hadoop.hbase.HRegionInfo;
42  import org.apache.hadoop.hbase.MiniHBaseCluster;
43  import org.apache.hadoop.hbase.NamespaceDescriptor;
44  import org.apache.hadoop.hbase.TableName;
45  import org.apache.hadoop.hbase.TableNotEnabledException;
46  import org.apache.hadoop.hbase.Waiter.Predicate;
47  import org.apache.hadoop.hbase.client.Connection;
48  import org.apache.hadoop.hbase.client.ConnectionFactory;
49  import org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException;
50  import org.apache.hadoop.hbase.client.Admin;
51  import org.apache.hadoop.hbase.client.Table;
52  import org.apache.hadoop.hbase.coprocessor.BaseMasterObserver;
53  import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
54  import org.apache.hadoop.hbase.coprocessor.ObserverContext;
55  import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment;
56  import org.apache.hadoop.hbase.io.hfile.HFile;
57  import org.apache.hadoop.hbase.master.HMaster;
58  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
59  import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos;
60  import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.AccessControlService;
61  import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.CheckPermissionsRequest;
62  import org.apache.hadoop.hbase.regionserver.Region;
63  import org.apache.hadoop.hbase.security.AccessDeniedException;
64  import org.apache.hadoop.hbase.security.User;
65  import org.apache.hadoop.hbase.security.access.Permission.Action;
66  import org.apache.hadoop.hbase.util.JVMClusterUtil.RegionServerThread;
67  
68  import com.google.common.collect.Lists;
69  import com.google.common.collect.Maps;
70  import com.google.protobuf.BlockingRpcChannel;
71  import com.google.protobuf.ServiceException;
72  
73  /**
74   * Utility methods for testing security
75   */
76  public class SecureTestUtil {
77  
78    private static final Log LOG = LogFactory.getLog(SecureTestUtil.class);
79    private static final int WAIT_TIME = 10000;
80  
81    public static void configureSuperuser(Configuration conf) throws IOException {
82      // The secure minicluster creates separate service principals based on the
83      // current user's name, one for each slave. We need to add all of these to
84      // the superuser list or security won't function properly. We expect the
85      // HBase service account(s) to have superuser privilege.
86      String currentUser = User.getCurrent().getName();
87      StringBuffer sb = new StringBuffer();
88      sb.append("admin,");
89      sb.append(currentUser);
90      // Assumes we won't ever have a minicluster with more than 5 slaves
91      for (int i = 0; i < 5; i++) {
92        sb.append(',');
93        sb.append(currentUser); sb.append(".hfs."); sb.append(i);
94      }
95      conf.set("hbase.superuser", sb.toString());
96    }
97  
98    public static void enableSecurity(Configuration conf) throws IOException {
99      conf.set("hadoop.security.authorization", "false");
100     conf.set("hadoop.security.authentication", "simple");
101     conf.set(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY, AccessController.class.getName() +
102       "," + MasterSyncObserver.class.getName());
103     conf.set(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY, AccessController.class.getName() +
104       "," + SecureBulkLoadEndpoint.class.getName());
105     conf.set(CoprocessorHost.REGIONSERVER_COPROCESSOR_CONF_KEY, AccessController.class.getName());
106     // Need HFile V3 for tags for security features
107     conf.setInt(HFile.FORMAT_VERSION_KEY, 3);
108     conf.setBoolean(User.HBASE_SECURITY_AUTHORIZATION_CONF_KEY, true);
109     configureSuperuser(conf);
110   }
111 
112   public static void verifyConfiguration(Configuration conf) {
113     String coprocs = conf.get(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY);
114     boolean accessControllerLoaded = false;
115     for (String coproc : coprocs.split(",")) {
116       try {
117         accessControllerLoaded = AccessController.class.isAssignableFrom(Class.forName(coproc));
118         if (accessControllerLoaded) break;
119       } catch (ClassNotFoundException cnfe) {
120       }
121     }
122     if (!(conf.get(CoprocessorHost.MASTER_COPROCESSOR_CONF_KEY).contains(
123         AccessController.class.getName())
124         && accessControllerLoaded && conf.get(
125         CoprocessorHost.REGIONSERVER_COPROCESSOR_CONF_KEY).contains(
126         AccessController.class.getName()))) {
127       throw new RuntimeException("AccessController is missing from a system coprocessor list");
128     }
129     if (conf.getInt(HFile.FORMAT_VERSION_KEY, 2) < HFile.MIN_FORMAT_VERSION_WITH_TAGS) {
130       throw new RuntimeException("Post 0.96 security features require HFile version >= 3");
131     }
132 
133     if (!conf.getBoolean(User.HBASE_SECURITY_AUTHORIZATION_CONF_KEY, false)) {
134       throw new RuntimeException("Post 1.5.0 security features require set "
135           + User.HBASE_SECURITY_AUTHORIZATION_CONF_KEY + " to true");
136     }
137   }
138 
139   public static void checkTablePerms(Configuration conf, TableName table, byte[] family, byte[] column,
140       Permission.Action... actions) throws IOException {
141     Permission[] perms = new Permission[actions.length];
142     for (int i = 0; i < actions.length; i++) {
143       perms[i] = new TablePermission(table, family, column, actions[i]);
144     }
145 
146     checkTablePerms(conf, table, perms);
147   }
148 
149   public static void checkTablePerms(Configuration conf, TableName table, Permission... perms)
150   throws IOException {
151     CheckPermissionsRequest.Builder request = CheckPermissionsRequest.newBuilder();
152     for (Permission p : perms) {
153       request.addPermission(ProtobufUtil.toPermission(p));
154     }
155     try (Connection connection = ConnectionFactory.createConnection(conf)) {
156       try (Table acl = connection.getTable(table)) {
157         AccessControlService.BlockingInterface protocol =
158             AccessControlService.newBlockingStub(acl.coprocessorService(new byte[0]));
159         try {
160           protocol.checkPermissions(null, request.build());
161         } catch (ServiceException se) {
162           ProtobufUtil.toIOException(se);
163         }
164       }
165     }
166   }
167 
168   /**
169    * An AccessTestAction performs an action that will be examined to confirm
170    * the results conform to expected access rights.
171    * <p>
172    * To indicate an action was allowed, return null or a non empty list of
173    * KeyValues.
174    * <p>
175    * To indicate the action was not allowed, either throw an AccessDeniedException
176    * or return an empty list of KeyValues.
177    */
178   public static interface AccessTestAction extends PrivilegedExceptionAction<Object> { }
179 
180   /** This fails only in case of ADE or empty list for any of the actions. */
181   public static void verifyAllowed(User user, AccessTestAction... actions) throws Exception {
182     for (AccessTestAction action : actions) {
183       try {
184         Object obj = user.runAs(action);
185         if (obj != null && obj instanceof List<?>) {
186           List<?> results = (List<?>) obj;
187           if (results != null && results.isEmpty()) {
188             fail("Empty non null results from action for user '" + user.getShortName() + "'");
189           }
190         }
191       } catch (AccessDeniedException ade) {
192         fail("Expected action to pass for user '" + user.getShortName() + "' but was denied");
193       }
194     }
195   }
196 
197   /** This fails only in case of ADE or empty list for any of the users. */
198   public static void verifyAllowed(AccessTestAction action, User... users) throws Exception {
199     for (User user : users) {
200       verifyAllowed(user, action);
201     }
202   }
203 
204   public static void verifyAllowed(User user, AccessTestAction action, int count) throws Exception {
205     try {
206       Object obj = user.runAs(action);
207       if (obj != null && obj instanceof List<?>) {
208         List<?> results = (List<?>) obj;
209         if (results != null && results.isEmpty()) {
210           fail("Empty non null results from action for user '" + user.getShortName() + "'");
211         }
212         assertEquals(count, results.size());
213       }
214     } catch (AccessDeniedException ade) {
215       fail("Expected action to pass for user '" + user.getShortName() + "' but was denied");
216     }
217   }
218 
219   /** This passes only in case of ADE for all users. */
220   public static void verifyDenied(AccessTestAction action, User... users) throws Exception {
221     for (User user : users) {
222       verifyDenied(user, action);
223     }
224   }
225 
226   /** This passes only in case of empty list for all users. */
227   public static void verifyIfEmptyList(AccessTestAction action, User... users) throws Exception {
228     for (User user : users) {
229       try {
230         Object obj = user.runAs(action);
231         if (obj != null && obj instanceof List<?>) {
232           List<?> results = (List<?>) obj;
233           if (results != null && !results.isEmpty()) {
234             fail("Unexpected action results: " +  results + " for user '"
235                 + user.getShortName() + "'");
236           }
237         } else {
238           fail("Unexpected results for user '" + user.getShortName() + "'");
239         }
240       } catch (AccessDeniedException ade) {
241         fail("Expected action to pass for user '" + user.getShortName() + "' but was denied");
242       }
243     }
244   }
245 
246   /** This passes only in case of null for all users. */
247   public static void verifyIfNull(AccessTestAction  action, User... users) throws Exception {
248     for (User user : users) {
249       try {
250         Object obj = user.runAs(action);
251         if (obj != null) {
252           fail("Non null results from action for user '" + user.getShortName() + "' : " + obj);
253         }
254       } catch (AccessDeniedException ade) {
255         fail("Expected action to pass for user '" + user.getShortName() + "' but was denied");
256       }
257     }
258   }
259 
260   /** This passes only in case of ADE for all actions. */
261   public static void verifyDenied(User user, AccessTestAction... actions) throws Exception {
262     for (AccessTestAction action : actions) {
263       try {
264         user.runAs(action);
265         fail("Expected exception was not thrown for user '" + user.getShortName() + "'");
266       } catch (IOException e) {
267         boolean isAccessDeniedException = false;
268         if(e instanceof RetriesExhaustedWithDetailsException) {
269           // in case of batch operations, and put, the client assembles a
270           // RetriesExhaustedWithDetailsException instead of throwing an
271           // AccessDeniedException
272           for(Throwable ex : ((RetriesExhaustedWithDetailsException) e).getCauses()) {
273             if (ex instanceof AccessDeniedException) {
274               isAccessDeniedException = true;
275               break;
276             }
277           }
278         }
279         else {
280           // For doBulkLoad calls AccessDeniedException
281           // is buried in the stack trace
282           Throwable ex = e;
283           do {
284             if (ex instanceof AccessDeniedException) {
285               isAccessDeniedException = true;
286               break;
287             }
288           } while((ex = ex.getCause()) != null);
289         }
290         if (!isAccessDeniedException) {
291           fail("Expected exception was not thrown for user '" + user.getShortName() + "'");
292         }
293       } catch (UndeclaredThrowableException ute) {
294         // TODO why we get a PrivilegedActionException, which is unexpected?
295         Throwable ex = ute.getUndeclaredThrowable();
296         if (ex instanceof PrivilegedActionException) {
297           ex = ((PrivilegedActionException) ex).getException();
298         }
299         if (ex instanceof ServiceException) {
300           ServiceException se = (ServiceException)ex;
301           if (se.getCause() != null && se.getCause() instanceof AccessDeniedException) {
302             // expected result
303             return;
304           }
305         }
306         fail("Expected exception was not thrown for user '" + user.getShortName() + "'");
307       }
308     }
309   }
310 
311   private static List<AccessController> getAccessControllers(MiniHBaseCluster cluster) {
312     List<AccessController> result = Lists.newArrayList();
313     for (RegionServerThread t: cluster.getLiveRegionServerThreads()) {
314       for (Region region: t.getRegionServer().getOnlineRegionsLocalContext()) {
315         Coprocessor cp = region.getCoprocessorHost()
316           .findCoprocessor(AccessController.class.getName());
317         if (cp != null) {
318           result.add((AccessController)cp);
319         }
320       }
321     }
322     return result;
323   }
324 
325   private static Map<AccessController,Long> getAuthManagerMTimes(MiniHBaseCluster cluster) {
326     Map<AccessController,Long> result = Maps.newHashMap();
327     for (AccessController ac: getAccessControllers(cluster)) {
328       result.put(ac, ac.getAuthManager().getMTime());
329     }
330     return result;
331   }
332 
333   @SuppressWarnings("rawtypes")
334   private static void updateACLs(final HBaseTestingUtility util, Callable c) throws Exception {
335     // Get the current mtimes for all access controllers
336     final Map<AccessController,Long> oldMTimes = getAuthManagerMTimes(util.getHBaseCluster());
337 
338     // Run the update action
339     c.call();
340 
341     // Wait until mtimes for all access controllers have incremented
342     util.waitFor(WAIT_TIME, 100, new Predicate<IOException>() {
343       @Override
344       public boolean evaluate() throws IOException {
345         Map<AccessController,Long> mtimes = getAuthManagerMTimes(util.getHBaseCluster());
346         for (Map.Entry<AccessController,Long> e: mtimes.entrySet()) {
347           if (!oldMTimes.containsKey(e.getKey())) {
348             LOG.error("Snapshot of AccessController state does not include instance on region " +
349               e.getKey().getRegion().getRegionInfo().getRegionNameAsString());
350             // Error out the predicate, we will try again
351             return false;
352           }
353           long old = oldMTimes.get(e.getKey());
354           long now = e.getValue();
355           if (now <= old) {
356             LOG.info("AccessController on region " +
357               e.getKey().getRegion().getRegionInfo().getRegionNameAsString() +
358               " has not updated: mtime=" + now);
359             return false;
360           }
361         }
362         return true;
363       }
364     });
365   }
366 
367   /**
368    * Grant permissions globally to the given user. Will wait until all active
369    * AccessController instances have updated their permissions caches or will
370    * throw an exception upon timeout (10 seconds).
371    */
372   public static void grantGlobal(final HBaseTestingUtility util, final String user,
373       final Permission.Action... actions) throws Exception {
374     SecureTestUtil.updateACLs(util, new Callable<Void>() {
375       @Override
376       public Void call() throws Exception {
377         try (Connection connection = ConnectionFactory.createConnection(util.getConfiguration())) {
378           try (Table acl = connection.getTable(AccessControlLists.ACL_TABLE_NAME)) {
379             BlockingRpcChannel service = acl.coprocessorService(HConstants.EMPTY_START_ROW);
380             AccessControlService.BlockingInterface protocol =
381                 AccessControlService.newBlockingStub(service);
382             ProtobufUtil.grant(null, protocol, user, false, actions);
383           }
384         }
385         return null;
386       }
387     });
388   }
389 
390   /**
391    * Revoke permissions globally from the given user. Will wait until all active
392    * AccessController instances have updated their permissions caches or will
393    * throw an exception upon timeout (10 seconds).
394    */
395   public static void revokeGlobal(final HBaseTestingUtility util, final String user,
396       final Permission.Action... actions) throws Exception {
397     SecureTestUtil.updateACLs(util, new Callable<Void>() {
398       @Override
399       public Void call() throws Exception {
400         try (Connection connection = ConnectionFactory.createConnection(util.getConfiguration())) {
401           try (Table acl = connection.getTable(AccessControlLists.ACL_TABLE_NAME)) {
402             BlockingRpcChannel service = acl.coprocessorService(HConstants.EMPTY_START_ROW);
403             AccessControlService.BlockingInterface protocol =
404                 AccessControlService.newBlockingStub(service);
405             ProtobufUtil.revoke(null, protocol, user, actions);
406           }
407         }
408         return null;
409       }
410     });
411   }
412 
413   /**
414    * Grant permissions on a namespace to the given user. Will wait until all active
415    * AccessController instances have updated their permissions caches or will
416    * throw an exception upon timeout (10 seconds).
417    */
418   public static void grantOnNamespace(final HBaseTestingUtility util, final String user,
419       final String namespace, final Permission.Action... actions) throws Exception {
420     SecureTestUtil.updateACLs(util, new Callable<Void>() {
421       @Override
422       public Void call() throws Exception {
423         try (Connection connection = ConnectionFactory.createConnection(util.getConfiguration())) {
424           try (Table acl = connection.getTable(AccessControlLists.ACL_TABLE_NAME)) {
425             BlockingRpcChannel service = acl.coprocessorService(HConstants.EMPTY_START_ROW);
426             AccessControlService.BlockingInterface protocol =
427                 AccessControlService.newBlockingStub(service);
428             ProtobufUtil.grant(null, protocol, user, namespace, false, actions);
429           }
430         }
431         return null;
432       }
433     });
434   }
435 
436   /**
437    * Grant permissions on a namespace to the given user using AccessControl Client.
438    * Will wait until all active AccessController instances have updated their permissions caches
439    * or will throw an exception upon timeout (10 seconds).
440    */
441   public static void grantOnNamespaceUsingAccessControlClient(final HBaseTestingUtility util,
442       final Connection connection, final String user, final String namespace,
443       final Permission.Action... actions) throws Exception {
444     SecureTestUtil.updateACLs(util, new Callable<Void>() {
445       @Override
446       public Void call() throws Exception {
447         try {
448           AccessControlClient.grant(connection, namespace, user, actions);
449         } catch (Throwable t) {
450           LOG.error("grant failed: ", t);
451         }
452         return null;
453       }
454     });
455   }
456 
457   public static void grantOnNamespaceUsingAccessControlClient(final HBaseTestingUtility util,
458       final Connection connection, final String user, final String namespace,
459       final boolean mergeExistingPermissions, final Permission.Action... actions) throws Exception {
460     SecureTestUtil.updateACLs(util, new Callable<Void>() {
461       @Override
462       public Void call() throws Exception {
463         try {
464           AccessControlClient.grant(connection, namespace, user, mergeExistingPermissions, actions);
465         } catch (Throwable t) {
466           LOG.error("grant failed: ", t);
467         }
468         return null;
469       }
470     });
471   }
472 
473   /**
474    * Revoke permissions on a namespace from the given user using AccessControl Client.
475    * Will wait until all active AccessController instances have updated their permissions caches
476    * or will throw an exception upon timeout (10 seconds).
477    */
478   public static void revokeFromNamespaceUsingAccessControlClient(final HBaseTestingUtility util,
479       final Connection connection, final String user, final String namespace,
480       final Permission.Action... actions) throws Exception {
481     SecureTestUtil.updateACLs(util, new Callable<Void>() {
482       @Override
483       public Void call() throws Exception {
484         try {
485           AccessControlClient.revoke(connection, namespace, user, actions);
486         } catch (Throwable t) {
487           LOG.error("revoke failed: ", t);
488         }
489         return null;
490       }
491     });
492   }
493 
494   /**
495    * Revoke permissions on a namespace from the given user. Will wait until all active
496    * AccessController instances have updated their permissions caches or will
497    * throw an exception upon timeout (10 seconds).
498    */
499   public static void revokeFromNamespace(final HBaseTestingUtility util, final String user,
500       final String namespace, final Permission.Action... actions) throws Exception {
501     SecureTestUtil.updateACLs(util, new Callable<Void>() {
502       @Override
503       public Void call() throws Exception {
504         try (Connection connection = ConnectionFactory.createConnection(util.getConfiguration())) {
505           try (Table acl = connection.getTable(AccessControlLists.ACL_TABLE_NAME)) {
506             BlockingRpcChannel service = acl.coprocessorService(HConstants.EMPTY_START_ROW);
507             AccessControlService.BlockingInterface protocol =
508                 AccessControlService.newBlockingStub(service);
509             ProtobufUtil.revoke(null, protocol, user, namespace, actions);
510           }
511         }
512         return null;
513       }
514     });
515   }
516 
517   /**
518    * Grant permissions on a table to the given user. Will wait until all active
519    * AccessController instances have updated their permissions caches or will
520    * throw an exception upon timeout (10 seconds).
521    */
522   public static void grantOnTable(final HBaseTestingUtility util, final String user,
523       final TableName table, final byte[] family, final byte[] qualifier,
524       final Permission.Action... actions) throws Exception {
525     SecureTestUtil.updateACLs(util, new Callable<Void>() {
526       @Override
527       public Void call() throws Exception {
528         try (Connection connection = ConnectionFactory.createConnection(util.getConfiguration())) {
529           try (Table acl = connection.getTable(AccessControlLists.ACL_TABLE_NAME)) {
530             BlockingRpcChannel service = acl.coprocessorService(HConstants.EMPTY_START_ROW);
531             AccessControlService.BlockingInterface protocol =
532                 AccessControlService.newBlockingStub(service);
533             ProtobufUtil.grant(null, protocol, user, table, family, qualifier, false, actions);
534           }
535         }
536         return null;
537       }
538     });
539   }
540 
541   /**
542    * Grant permissions on a table to the given user using AccessControlClient. Will wait until all
543    * active AccessController instances have updated their permissions caches or will
544    * throw an exception upon timeout (10 seconds).
545    */
546   public static void grantOnTableUsingAccessControlClient(final HBaseTestingUtility util,
547       final Connection connection, final String user, final TableName table, final byte[] family,
548       final byte[] qualifier, final Permission.Action... actions) throws Exception {
549     SecureTestUtil.updateACLs(util, new Callable<Void>() {
550       @Override
551       public Void call() throws Exception {
552         try {
553           AccessControlClient.grant(connection, table, user, family, qualifier, actions);
554         } catch (Throwable t) {
555           LOG.error("grant failed: ", t);
556         }
557         return null;
558       }
559     });
560   }
561 
562   public static void grantOnTableUsingAccessControlClient(final HBaseTestingUtility util,
563       final Connection connection, final String user, final TableName table, final byte[] family,
564       final byte[] qualifier, final boolean mergeExistingPermissions,
565       final Permission.Action... actions) throws Exception {
566     SecureTestUtil.updateACLs(util, new Callable<Void>() {
567       @Override
568       public Void call() throws Exception {
569         try {
570           AccessControlClient.grant(connection, table, user, family, qualifier,
571             mergeExistingPermissions, actions);
572         } catch (Throwable t) {
573           LOG.error("grant failed: ", t);
574         }
575         return null;
576       }
577     });
578   }
579 
580 
581 
582   /**
583    * Grant global permissions to the given user using AccessControlClient. Will wait until all
584    * active AccessController instances have updated their permissions caches or will
585    * throw an exception upon timeout (10 seconds).
586    */
587   public static void grantGlobalUsingAccessControlClient(final HBaseTestingUtility util,
588       final Connection connection, final String user, final Permission.Action... actions)
589       throws Exception {
590     SecureTestUtil.updateACLs(util, new Callable<Void>() {
591       @Override
592       public Void call() throws Exception {
593         try {
594           AccessControlClient.grant(connection, user, actions);
595         } catch (Throwable t) {
596           LOG.error("grant failed: ", t);
597         }
598         return null;
599       }
600     });
601   }
602 
603   public static void grantGlobalUsingAccessControlClient(final HBaseTestingUtility util,
604       final Connection connection, final String user, final boolean mergeExistingPermissions,
605       final Permission.Action... actions) throws Exception {
606     SecureTestUtil.updateACLs(util, new Callable<Void>() {
607       @Override
608       public Void call() throws Exception {
609         try {
610           AccessControlClient.grant(connection, user, mergeExistingPermissions, actions);
611         } catch (Throwable t) {
612           LOG.error("grant failed: ", t);
613         }
614         return null;
615       }
616     });
617   }
618 
619   /**
620    * Revoke permissions on a table from the given user. Will wait until all active
621    * AccessController instances have updated their permissions caches or will
622    * throw an exception upon timeout (10 seconds).
623    */
624   public static void revokeFromTable(final HBaseTestingUtility util, final String user,
625       final TableName table, final byte[] family, final byte[] qualifier,
626       final Permission.Action... actions) throws Exception {
627     SecureTestUtil.updateACLs(util, new Callable<Void>() {
628       @Override
629       public Void call() throws Exception {
630         try (Connection connection = ConnectionFactory.createConnection(util.getConfiguration())) {
631           try (Table acl = connection.getTable(AccessControlLists.ACL_TABLE_NAME)) {
632             BlockingRpcChannel service = acl.coprocessorService(HConstants.EMPTY_START_ROW);
633             AccessControlService.BlockingInterface protocol =
634                 AccessControlService.newBlockingStub(service);
635             ProtobufUtil.revoke(null, protocol, user, table, family, qualifier, actions);
636           }
637         }
638         return null;
639       }
640     });
641   }
642 
643   /**
644    * Revoke permissions on a table from the given user using AccessControlClient. Will wait until
645    * all active AccessController instances have updated their permissions caches or will
646    * throw an exception upon timeout (10 seconds).
647    */
648   public static void revokeFromTableUsingAccessControlClient(final HBaseTestingUtility util,
649       final Connection connection, final String user, final TableName table, final byte[] family,
650       final byte[] qualifier, final Permission.Action... actions) throws Exception {
651     SecureTestUtil.updateACLs(util, new Callable<Void>() {
652       @Override
653       public Void call() throws Exception {
654         try {
655           AccessControlClient.revoke(connection, table, user, family, qualifier, actions);
656         } catch (Throwable t) {
657           LOG.error("revoke failed: ", t);
658         }
659         return null;
660       }
661     });
662   }
663 
664   /**
665    * Revoke global permissions from the given user using AccessControlClient. Will wait until
666    * all active AccessController instances have updated their permissions caches or will
667    * throw an exception upon timeout (10 seconds).
668    */
669   public static void revokeGlobalUsingAccessControlClient(final HBaseTestingUtility util,
670       final Connection connection, final String user,final Permission.Action... actions)
671       throws Exception {
672     SecureTestUtil.updateACLs(util, new Callable<Void>() {
673       @Override
674       public Void call() throws Exception {
675         try {
676           AccessControlClient.revoke(connection, user, actions);
677         } catch (Throwable t) {
678           LOG.error("revoke failed: ", t);
679         }
680         return null;
681       }
682     });
683   }
684 
685   public static class MasterSyncObserver extends BaseMasterObserver {
686     volatile CountDownLatch tableCreationLatch = null;
687     volatile CountDownLatch tableDeletionLatch = null;
688 
689     @Override
690     public void postCreateTableHandler(
691         final ObserverContext<MasterCoprocessorEnvironment> ctx,
692         HTableDescriptor desc, HRegionInfo[] regions) throws IOException {
693       // the AccessController test, some times calls only and directly the postCreateTableHandler()
694       if (tableCreationLatch != null) {
695         tableCreationLatch.countDown();
696       }
697     }
698 
699     @Override
700     public void postDeleteTableHandler(
701         final ObserverContext<MasterCoprocessorEnvironment> ctx, TableName tableName)
702         throws IOException {
703       // the AccessController test, some times calls only and directly the postDeleteTableHandler()
704       if (tableDeletionLatch != null) {
705         tableDeletionLatch.countDown();
706       }
707     }
708   }
709 
710   public static Table createTable(HBaseTestingUtility testUtil, TableName tableName,
711       byte[][] families) throws Exception {
712     HTableDescriptor htd = new HTableDescriptor(tableName);
713     for (byte[] family : families) {
714       HColumnDescriptor hcd = new HColumnDescriptor(family);
715       htd.addFamily(hcd);
716     }
717     createTable(testUtil, testUtil.getHBaseAdmin(), htd);
718     return testUtil.getConnection().getTable(htd.getTableName());
719   }
720 
721   public static void createTable(HBaseTestingUtility testUtil, HTableDescriptor htd)
722       throws Exception {
723     createTable(testUtil, testUtil.getHBaseAdmin(), htd);
724   }
725 
726   public static void createTable(HBaseTestingUtility testUtil, HTableDescriptor htd,
727       byte[][] splitKeys) throws Exception {
728     createTable(testUtil, testUtil.getHBaseAdmin(), htd, splitKeys);
729   }
730 
731   public static void createTable(HBaseTestingUtility testUtil, Admin admin, HTableDescriptor htd)
732       throws Exception {
733     createTable(testUtil, admin, htd, null);
734   }
735 
736   public static void createTable(HBaseTestingUtility testUtil, Admin admin, HTableDescriptor htd,
737       byte[][] splitKeys) throws Exception {
738     // NOTE: We need a latch because admin is not sync,
739     // so the postOp coprocessor method may be called after the admin operation returned.
740     MasterSyncObserver observer = (MasterSyncObserver)testUtil.getHBaseCluster().getMaster()
741       .getMasterCoprocessorHost().findCoprocessor(MasterSyncObserver.class.getName());
742     observer.tableCreationLatch = new CountDownLatch(1);
743     if (splitKeys != null) {
744       admin.createTable(htd, splitKeys);
745     } else {
746       admin.createTable(htd);
747     }
748     observer.tableCreationLatch.await();
749     observer.tableCreationLatch = null;
750     testUtil.waitUntilAllRegionsAssigned(htd.getTableName());
751   }
752 
753   public static void deleteTable(HBaseTestingUtility testUtil, TableName tableName)
754       throws Exception {
755     deleteTable(testUtil, testUtil.getHBaseAdmin(), tableName);
756   }
757 
758   public static void createNamespace(HBaseTestingUtility testUtil, NamespaceDescriptor nsDesc)
759       throws Exception {
760     testUtil.getHBaseAdmin().createNamespace(nsDesc);
761   }
762 
763   public static void deleteNamespace(HBaseTestingUtility testUtil, String namespace)
764       throws Exception {
765     testUtil.getHBaseAdmin().deleteNamespace(namespace);
766   }
767 
768   public static void deleteTable(HBaseTestingUtility testUtil, Admin admin, TableName tableName)
769       throws Exception {
770     // NOTE: We need a latch because admin is not sync,
771     // so the postOp coprocessor method may be called after the admin operation returned.
772     MasterSyncObserver observer = null;
773     HMaster master = testUtil.getHBaseCluster().getMaster();
774     if (master != null) {
775       observer = (MasterSyncObserver)master.getMasterCoprocessorHost()
776           .findCoprocessor(MasterSyncObserver.class.getName());
777       if (observer != null) {
778         observer.tableDeletionLatch = new CountDownLatch(1);
779       }
780     }
781     try {
782       admin.disableTable(tableName);
783     } catch (TableNotEnabledException e) {
784       LOG.debug("Table: " + tableName + " already disabled, so just deleting it.");
785     }
786     admin.deleteTable(tableName);
787     if (observer != null) {
788       observer.tableDeletionLatch.await();
789       observer.tableDeletionLatch = null;
790     }
791   }
792 
793   public static String convertToNamespace(String namespace) {
794     return AccessControlLists.NAMESPACE_PREFIX + namespace;
795   }
796 
797   public static void checkGlobalPerms(HBaseTestingUtility testUtil, Permission.Action... actions)
798       throws IOException {
799     Permission[] perms = new Permission[actions.length];
800     for (int i = 0; i < actions.length; i++) {
801       perms[i] = new Permission(actions[i]);
802     }
803     CheckPermissionsRequest.Builder request = CheckPermissionsRequest.newBuilder();
804     for (Action a : actions) {
805       request.addPermission(AccessControlProtos.Permission.newBuilder()
806           .setType(AccessControlProtos.Permission.Type.Global)
807           .setGlobalPermission(
808               AccessControlProtos.GlobalPermission.newBuilder()
809                   .addAction(ProtobufUtil.toPermissionAction(a)).build()));
810     }
811     try(Connection conn = ConnectionFactory.createConnection(testUtil.getConfiguration());
812         Table acl = conn.getTable(AccessControlLists.ACL_TABLE_NAME)) {
813       BlockingRpcChannel channel = acl.coprocessorService(new byte[0]);
814       AccessControlService.BlockingInterface protocol =
815         AccessControlService.newBlockingStub(channel);
816       try {
817         protocol.checkPermissions(null, request.build());
818       } catch (ServiceException se) {
819         ProtobufUtil.toIOException(se);
820       }
821     }
822   }
823 
824   public static void checkTablePerms(HBaseTestingUtility testUtil, TableName table, byte[] family,
825       byte[] column, Permission.Action... actions) throws IOException {
826     Permission[] perms = new Permission[actions.length];
827     for (int i = 0; i < actions.length; i++) {
828       perms[i] = new TablePermission(table, family, column, actions[i]);
829     }
830     checkTablePerms(testUtil, table, perms);
831   }
832 
833   public static void checkTablePerms(HBaseTestingUtility testUtil, TableName table,
834       Permission... perms) throws IOException {
835     CheckPermissionsRequest.Builder request = CheckPermissionsRequest.newBuilder();
836     for (Permission p : perms) {
837       request.addPermission(ProtobufUtil.toPermission(p));
838     }
839 
840     try(Connection conn = ConnectionFactory.createConnection(testUtil.getConfiguration());
841         Table acl = conn.getTable(table)) {
842       AccessControlService.BlockingInterface protocol =
843         AccessControlService.newBlockingStub(acl.coprocessorService(new byte[0]));
844       try {
845         protocol.checkPermissions(null, request.build());
846       } catch (ServiceException se) {
847         ProtobufUtil.toIOException(se);
848       }
849     }
850   }
851 
852 }