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.assertFalse;
23  import static org.junit.Assert.assertNotNull;
24  import static org.junit.Assert.assertTrue;
25  import static org.junit.Assert.fail;
26  
27  import java.io.IOException;
28  import java.security.PrivilegedAction;
29  import java.util.Arrays;
30  import java.util.List;
31  
32  import org.apache.commons.logging.Log;
33  import org.apache.commons.logging.LogFactory;
34  import org.apache.hadoop.conf.Configuration;
35  import org.apache.hadoop.fs.FileStatus;
36  import org.apache.hadoop.fs.FileSystem;
37  import org.apache.hadoop.fs.Path;
38  import org.apache.hadoop.fs.permission.FsPermission;
39  import org.apache.hadoop.hbase.Coprocessor;
40  import org.apache.hadoop.hbase.CoprocessorEnvironment;
41  import org.apache.hadoop.hbase.HBaseTestingUtility;
42  import org.apache.hadoop.hbase.HColumnDescriptor;
43  import org.apache.hadoop.hbase.HConstants;
44  import org.apache.hadoop.hbase.HRegionInfo;
45  import org.apache.hadoop.hbase.HRegionLocation;
46  import org.apache.hadoop.hbase.HTableDescriptor;
47  import org.apache.hadoop.hbase.KeyValue;
48  import org.apache.hadoop.hbase.testclassification.LargeTests;
49  import org.apache.hadoop.hbase.MiniHBaseCluster;
50  import org.apache.hadoop.hbase.NamespaceDescriptor;
51  import org.apache.hadoop.hbase.ServerName;
52  import org.apache.hadoop.hbase.TableName;
53  import org.apache.hadoop.hbase.TableNotFoundException;
54  import org.apache.hadoop.hbase.Tag;
55  import org.apache.hadoop.hbase.client.Admin;
56  import org.apache.hadoop.hbase.client.Append;
57  import org.apache.hadoop.hbase.client.Connection;
58  import org.apache.hadoop.hbase.client.ConnectionFactory;
59  import org.apache.hadoop.hbase.client.Delete;
60  import org.apache.hadoop.hbase.client.Get;
61  import org.apache.hadoop.hbase.client.HTable;
62  import org.apache.hadoop.hbase.client.Increment;
63  import org.apache.hadoop.hbase.client.Put;
64  import org.apache.hadoop.hbase.client.RegionLocator;
65  import org.apache.hadoop.hbase.client.Result;
66  import org.apache.hadoop.hbase.client.ResultScanner;
67  import org.apache.hadoop.hbase.client.Scan;
68  import org.apache.hadoop.hbase.client.Table;
69  import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
70  import org.apache.hadoop.hbase.coprocessor.CoprocessorService;
71  import org.apache.hadoop.hbase.coprocessor.MasterCoprocessorEnvironment;
72  import org.apache.hadoop.hbase.coprocessor.ObserverContext;
73  import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
74  import org.apache.hadoop.hbase.coprocessor.RegionServerCoprocessorEnvironment;
75  import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.CountRequest;
76  import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.CountResponse;
77  import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.HelloRequest;
78  import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.HelloResponse;
79  import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.IncrementCountRequest;
80  import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.IncrementCountResponse;
81  import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.NoopRequest;
82  import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.NoopResponse;
83  import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.PingRequest;
84  import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.PingResponse;
85  import org.apache.hadoop.hbase.coprocessor.protobuf.generated.PingProtos.PingService;
86  import org.apache.hadoop.hbase.exceptions.HBaseException;
87  import org.apache.hadoop.hbase.io.hfile.CacheConfig;
88  import org.apache.hadoop.hbase.io.hfile.HFile;
89  import org.apache.hadoop.hbase.io.hfile.HFileContext;
90  import org.apache.hadoop.hbase.io.hfile.HFileContextBuilder;
91  import org.apache.hadoop.hbase.mapreduce.LoadIncrementalHFiles;
92  import org.apache.hadoop.hbase.master.MasterCoprocessorHost;
93  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
94  import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos;
95  import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.AccessControlService;
96  import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos.CheckPermissionsRequest;
97  import org.apache.hadoop.hbase.protobuf.generated.HBaseProtos.SnapshotDescription;
98  import org.apache.hadoop.hbase.regionserver.HRegion;
99  import org.apache.hadoop.hbase.regionserver.HRegionServer;
100 import org.apache.hadoop.hbase.regionserver.Region;
101 import org.apache.hadoop.hbase.regionserver.RegionCoprocessorHost;
102 import org.apache.hadoop.hbase.regionserver.RegionServerCoprocessorHost;
103 import org.apache.hadoop.hbase.regionserver.ScanType;
104 import org.apache.hadoop.hbase.security.User;
105 import org.apache.hadoop.hbase.security.access.Permission.Action;
106 import org.apache.hadoop.hbase.util.Bytes;
107 import org.apache.hadoop.hbase.util.JVMClusterUtil;
108 import org.apache.hadoop.hbase.util.TestTableName;
109 import org.apache.log4j.Level;
110 import org.apache.log4j.Logger;
111 import org.junit.After;
112 import org.junit.AfterClass;
113 import org.junit.Before;
114 import org.junit.BeforeClass;
115 import org.junit.Rule;
116 import org.junit.Test;
117 import org.junit.experimental.categories.Category;
118 
119 import com.google.protobuf.BlockingRpcChannel;
120 import com.google.protobuf.RpcCallback;
121 import com.google.protobuf.RpcController;
122 import com.google.protobuf.Service;
123 import com.google.protobuf.ServiceException;
124 
125 /**
126  * Performs authorization checks for common operations, according to different
127  * levels of authorized users.
128  */
129 @Category(LargeTests.class)
130 public class TestAccessController extends SecureTestUtil {
131   private static final Log LOG = LogFactory.getLog(TestAccessController.class);
132 
133   static {
134     Logger.getLogger(AccessController.class).setLevel(Level.TRACE);
135     Logger.getLogger(AccessControlFilter.class).setLevel(Level.TRACE);
136     Logger.getLogger(TableAuthManager.class).setLevel(Level.TRACE);
137   }
138 
139   @Rule public TestTableName TEST_TABLE = new TestTableName();
140   private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
141   private static Configuration conf;
142 
143   /** The systemUserConnection created here is tied to the system user. In case, you are planning
144    * to create AccessTestAction, DON'T use this systemUserConnection as the 'doAs' user
145    * gets  eclipsed by the system user. */
146   private static Connection systemUserConnection;
147 
148 
149   // user with all permissions
150   private static User SUPERUSER;
151   // user granted with all global permission
152   private static User USER_ADMIN;
153   // user with rw permissions on column family.
154   private static User USER_RW;
155   // user with read-only permissions
156   private static User USER_RO;
157   // user is table owner. will have all permissions on table
158   private static User USER_OWNER;
159   // user with create table permissions alone
160   private static User USER_CREATE;
161   // user with no permissions
162   private static User USER_NONE;
163   // user with admin rights on the column family
164   private static User USER_ADMIN_CF;
165 
166   // TODO: convert this test to cover the full matrix in
167   // https://hbase.apache.org/book/appendix_acl_matrix.html
168   // creating all Scope x Permission combinations
169 
170   private static TableName TEST_TABLE2 = TableName.valueOf("testtable2");
171   private static byte[] TEST_FAMILY = Bytes.toBytes("f1");
172   private static byte[] TEST_QUALIFIER = Bytes.toBytes("q1");
173   private static byte[] TEST_ROW = Bytes.toBytes("r1");
174 
175   private static MasterCoprocessorEnvironment CP_ENV;
176   private static AccessController ACCESS_CONTROLLER;
177   private static RegionServerCoprocessorEnvironment RSCP_ENV;
178   private RegionCoprocessorEnvironment RCP_ENV;
179 
180   @BeforeClass
181   public static void setupBeforeClass() throws Exception {
182     // setup configuration
183     conf = TEST_UTIL.getConfiguration();
184     // Enable security
185     enableSecurity(conf);
186     // In this particular test case, we can't use SecureBulkLoadEndpoint because its doAs will fail
187     // to move a file for a random user
188     conf.set(CoprocessorHost.REGION_COPROCESSOR_CONF_KEY, AccessController.class.getName());
189     // Verify enableSecurity sets up what we require
190     verifyConfiguration(conf);
191 
192     // Enable EXEC permission checking
193     conf.setBoolean(AccessControlConstants.EXEC_PERMISSION_CHECKS_KEY, true);
194 
195     TEST_UTIL.startMiniCluster();
196     MasterCoprocessorHost cpHost =
197       TEST_UTIL.getMiniHBaseCluster().getMaster().getMasterCoprocessorHost();
198     cpHost.load(AccessController.class, Coprocessor.PRIORITY_HIGHEST, conf);
199     ACCESS_CONTROLLER = (AccessController) cpHost.findCoprocessor(AccessController.class.getName());
200     CP_ENV = cpHost.createEnvironment(AccessController.class, ACCESS_CONTROLLER,
201       Coprocessor.PRIORITY_HIGHEST, 1, conf);
202     RegionServerCoprocessorHost rsHost = TEST_UTIL.getMiniHBaseCluster().getRegionServer(0)
203       .getRegionServerCoprocessorHost();
204     RSCP_ENV = rsHost.createEnvironment(AccessController.class, ACCESS_CONTROLLER,
205       Coprocessor.PRIORITY_HIGHEST, 1, conf);
206 
207     // Wait for the ACL table to become available
208     TEST_UTIL.waitUntilAllRegionsAssigned(AccessControlLists.ACL_TABLE_NAME);
209 
210     // create a set of test users
211     SUPERUSER = User.createUserForTesting(conf, "admin", new String[] { "supergroup" });
212     USER_ADMIN = User.createUserForTesting(conf, "admin2", new String[0]);
213     USER_RW = User.createUserForTesting(conf, "rwuser", new String[0]);
214     USER_RO = User.createUserForTesting(conf, "rouser", new String[0]);
215     USER_OWNER = User.createUserForTesting(conf, "owner", new String[0]);
216     USER_CREATE = User.createUserForTesting(conf, "tbl_create", new String[0]);
217     USER_NONE = User.createUserForTesting(conf, "nouser", new String[0]);
218     USER_ADMIN_CF = User.createUserForTesting(conf, "col_family_admin", new String[0]);
219 
220     systemUserConnection = TEST_UTIL.getConnection();
221   }
222 
223   @AfterClass
224   public static void tearDownAfterClass() throws Exception {
225     TEST_UTIL.shutdownMiniCluster();
226   }
227 
228   @Before
229   public void setUp() throws Exception {
230     // Create the test table (owner added to the _acl_ table)
231     Admin admin = TEST_UTIL.getHBaseAdmin();
232     HTableDescriptor htd = new HTableDescriptor(TEST_TABLE.getTableName());
233     HColumnDescriptor hcd = new HColumnDescriptor(TEST_FAMILY);
234     hcd.setMaxVersions(100);
235     htd.addFamily(hcd);
236     htd.setOwner(USER_OWNER);
237     createTable(TEST_UTIL, htd, new byte[][] { Bytes.toBytes("s") });
238 
239     Region region = TEST_UTIL.getHBaseCluster().getRegions(TEST_TABLE.getTableName()).get(0);
240     RegionCoprocessorHost rcpHost = region.getCoprocessorHost();
241     RCP_ENV = rcpHost.createEnvironment(AccessController.class, ACCESS_CONTROLLER,
242       Coprocessor.PRIORITY_HIGHEST, 1, conf);
243 
244     // Set up initial grants
245 
246     grantGlobal(TEST_UTIL, USER_ADMIN.getShortName(),
247       Permission.Action.ADMIN,
248       Permission.Action.CREATE,
249       Permission.Action.READ,
250       Permission.Action.WRITE);
251 
252     grantOnTable(TEST_UTIL, USER_RW.getShortName(),
253       TEST_TABLE.getTableName(), TEST_FAMILY, null,
254       Permission.Action.READ,
255       Permission.Action.WRITE);
256 
257     // USER_CREATE is USER_RW plus CREATE permissions
258     grantOnTable(TEST_UTIL, USER_CREATE.getShortName(),
259       TEST_TABLE.getTableName(), null, null,
260       Permission.Action.CREATE,
261       Permission.Action.READ,
262       Permission.Action.WRITE);
263 
264     grantOnTable(TEST_UTIL, USER_RO.getShortName(),
265       TEST_TABLE.getTableName(), TEST_FAMILY, null,
266       Permission.Action.READ);
267 
268     grantOnTable(TEST_UTIL, USER_ADMIN_CF.getShortName(),
269       TEST_TABLE.getTableName(), TEST_FAMILY,
270       null, Permission.Action.ADMIN, Permission.Action.CREATE);
271 
272     assertEquals(5, AccessControlLists.getTablePermissions(conf, TEST_TABLE.getTableName()).size());
273     try {
274       assertEquals(5, AccessControlClient.getUserPermissions(systemUserConnection,
275           TEST_TABLE.toString()).size());
276     } catch (Throwable e) {
277       LOG.error("error during call of AccessControlClient.getUserPermissions. ", e);
278     }
279   }
280 
281   @After
282   public void tearDown() throws Exception {
283     // Clean the _acl_ table
284     try {
285       deleteTable(TEST_UTIL, TEST_TABLE.getTableName());
286     } catch (TableNotFoundException ex) {
287       // Test deleted the table, no problem
288       LOG.info("Test deleted table " + TEST_TABLE.getTableName());
289     }
290     // Verify all table/namespace permissions are erased
291     assertEquals(0, AccessControlLists.getTablePermissions(conf, TEST_TABLE.getTableName()).size());
292     assertEquals(
293       0,
294       AccessControlLists.getNamespacePermissions(conf,
295         TEST_TABLE.getTableName().getNamespaceAsString()).size());
296   }
297 
298   @Test
299   public void testTableCreate() throws Exception {
300     AccessTestAction createTable = new AccessTestAction() {
301       @Override
302       public Object run() throws Exception {
303         HTableDescriptor htd = new HTableDescriptor(TableName.valueOf("testnewtable"));
304         htd.addFamily(new HColumnDescriptor(TEST_FAMILY));
305         ACCESS_CONTROLLER.preCreateTable(ObserverContext.createAndPrepare(CP_ENV, null), htd, null);
306         return null;
307       }
308     };
309 
310     // verify that superuser can create tables
311     verifyAllowed(createTable, SUPERUSER, USER_ADMIN);
312 
313     // all others should be denied
314     verifyDenied(createTable, USER_CREATE, USER_RW, USER_RO, USER_NONE);
315   }
316 
317   @Test
318   public void testTableModify() throws Exception {
319     AccessTestAction modifyTable = new AccessTestAction() {
320       @Override
321       public Object run() throws Exception {
322         HTableDescriptor htd = new HTableDescriptor(TEST_TABLE.getTableName());
323         htd.addFamily(new HColumnDescriptor(TEST_FAMILY));
324         htd.addFamily(new HColumnDescriptor("fam_" + User.getCurrent().getShortName()));
325         ACCESS_CONTROLLER.preModifyTable(ObserverContext.createAndPrepare(CP_ENV, null),
326           TEST_TABLE.getTableName(), htd);
327         return null;
328       }
329     };
330 
331     verifyAllowed(modifyTable, SUPERUSER, USER_ADMIN, USER_CREATE, USER_OWNER);
332     verifyDenied(modifyTable, USER_RW, USER_RO, USER_NONE);
333   }
334 
335   @Test
336   public void testTableDelete() throws Exception {
337     AccessTestAction deleteTable = new AccessTestAction() {
338       @Override
339       public Object run() throws Exception {
340         ACCESS_CONTROLLER
341             .preDeleteTable(ObserverContext.createAndPrepare(CP_ENV, null), TEST_TABLE.getTableName());
342         return null;
343       }
344     };
345 
346     verifyAllowed(deleteTable, SUPERUSER, USER_ADMIN, USER_CREATE, USER_OWNER);
347     verifyDenied(deleteTable, USER_RW, USER_RO, USER_NONE);
348   }
349 
350   @Test
351   public void testTableTruncate() throws Exception {
352     AccessTestAction truncateTable = new AccessTestAction() {
353       @Override
354       public Object run() throws Exception {
355         ACCESS_CONTROLLER
356             .preTruncateTable(ObserverContext.createAndPrepare(CP_ENV, null),
357               TEST_TABLE.getTableName());
358         return null;
359       }
360     };
361 
362     verifyAllowed(truncateTable, SUPERUSER, USER_ADMIN, USER_CREATE, USER_OWNER);
363     verifyDenied(truncateTable, USER_RW, USER_RO, USER_NONE);
364   }
365 
366   @Test
367   public void testAddColumn() throws Exception {
368     final HColumnDescriptor hcd = new HColumnDescriptor("fam_new");
369     AccessTestAction action = new AccessTestAction() {
370       @Override
371       public Object run() throws Exception {
372         ACCESS_CONTROLLER.preAddColumn(ObserverContext.createAndPrepare(CP_ENV, null), TEST_TABLE.getTableName(),
373           hcd);
374         return null;
375       }
376     };
377 
378     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_CREATE, USER_OWNER);
379     verifyDenied(action, USER_RW, USER_RO, USER_NONE);
380   }
381 
382   @Test
383   public void testModifyColumn() throws Exception {
384     final HColumnDescriptor hcd = new HColumnDescriptor(TEST_FAMILY);
385     hcd.setMaxVersions(10);
386     AccessTestAction action = new AccessTestAction() {
387       @Override
388       public Object run() throws Exception {
389         ACCESS_CONTROLLER.preModifyColumn(ObserverContext.createAndPrepare(CP_ENV, null),
390           TEST_TABLE.getTableName(), hcd);
391         return null;
392       }
393     };
394 
395     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_CREATE, USER_OWNER, USER_ADMIN_CF);
396     verifyDenied(action, USER_RW, USER_RO, USER_NONE);
397   }
398 
399   @Test
400   public void testDeleteColumn() throws Exception {
401     AccessTestAction action = new AccessTestAction() {
402       @Override
403       public Object run() throws Exception {
404         ACCESS_CONTROLLER.preDeleteColumn(ObserverContext.createAndPrepare(CP_ENV, null),
405           TEST_TABLE.getTableName(), TEST_FAMILY);
406         return null;
407       }
408     };
409 
410     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_CREATE, USER_OWNER, USER_ADMIN_CF);
411     verifyDenied(action, USER_RW, USER_RO, USER_NONE);
412   }
413 
414   @Test
415   public void testTableDisable() throws Exception {
416     AccessTestAction disableTable = new AccessTestAction() {
417       @Override
418       public Object run() throws Exception {
419         ACCESS_CONTROLLER.preDisableTable(ObserverContext.createAndPrepare(CP_ENV, null),
420           TEST_TABLE.getTableName());
421         return null;
422       }
423     };
424 
425     AccessTestAction disableAclTable = new AccessTestAction() {
426       @Override
427       public Object run() throws Exception {
428         ACCESS_CONTROLLER.preDisableTable(ObserverContext.createAndPrepare(CP_ENV, null),
429             AccessControlLists.ACL_TABLE_NAME);
430         return null;
431       }
432     };
433 
434     verifyAllowed(disableTable, SUPERUSER, USER_ADMIN, USER_CREATE, USER_OWNER);
435     verifyDenied(disableTable, USER_RW, USER_RO, USER_NONE);
436 
437     // No user should be allowed to disable _acl_ table
438     verifyDenied(disableAclTable, SUPERUSER, USER_ADMIN, USER_CREATE, USER_OWNER, USER_RW, USER_RO);
439   }
440 
441   @Test
442   public void testTableEnable() throws Exception {
443     AccessTestAction enableTable = new AccessTestAction() {
444       @Override
445       public Object run() throws Exception {
446         ACCESS_CONTROLLER
447             .preEnableTable(ObserverContext.createAndPrepare(CP_ENV, null), TEST_TABLE.getTableName());
448         return null;
449       }
450     };
451 
452     verifyAllowed(enableTable, SUPERUSER, USER_ADMIN, USER_CREATE, USER_OWNER);
453     verifyDenied(enableTable, USER_RW, USER_RO, USER_NONE);
454   }
455 
456   @Test
457   public void testMove() throws Exception {
458     List<HRegionLocation> regions;
459     try (RegionLocator locator = systemUserConnection.getRegionLocator(TEST_TABLE.getTableName())) {
460       regions = locator.getAllRegionLocations();
461     }
462     HRegionLocation location = regions.get(0);
463     final HRegionInfo hri = location.getRegionInfo();
464     final ServerName server = location.getServerName();
465     AccessTestAction action = new AccessTestAction() {
466       @Override
467       public Object run() throws Exception {
468         ACCESS_CONTROLLER.preMove(ObserverContext.createAndPrepare(CP_ENV, null),
469           hri, server, server);
470         return null;
471       }
472     };
473 
474     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWNER);
475     verifyDenied(action, USER_CREATE, USER_RW, USER_RO, USER_NONE);
476   }
477 
478   @Test
479   public void testAssign() throws Exception {
480     List<HRegionLocation> regions;
481     try (RegionLocator locator = systemUserConnection.getRegionLocator(TEST_TABLE.getTableName())) {
482       regions = locator.getAllRegionLocations();
483     }
484     HRegionLocation location = regions.get(0);
485     final HRegionInfo hri = location.getRegionInfo();
486     AccessTestAction action = new AccessTestAction() {
487       @Override
488       public Object run() throws Exception {
489         ACCESS_CONTROLLER.preAssign(ObserverContext.createAndPrepare(CP_ENV, null), hri);
490         return null;
491       }
492     };
493 
494     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWNER);
495     verifyDenied(action, USER_CREATE, USER_RW, USER_RO, USER_NONE);
496   }
497 
498   @Test
499   public void testUnassign() throws Exception {
500     List<HRegionLocation> regions;
501     try (RegionLocator locator = systemUserConnection.getRegionLocator(TEST_TABLE.getTableName())) {
502       regions = locator.getAllRegionLocations();
503     }
504     HRegionLocation location = regions.get(0);
505     final HRegionInfo hri = location.getRegionInfo();
506     AccessTestAction action = new AccessTestAction() {
507       @Override
508       public Object run() throws Exception {
509         ACCESS_CONTROLLER.preUnassign(ObserverContext.createAndPrepare(CP_ENV, null), hri, false);
510         return null;
511       }
512     };
513 
514     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWNER);
515     verifyDenied(action, USER_CREATE, USER_RW, USER_RO, USER_NONE);
516   }
517 
518   @Test
519   public void testRegionOffline() throws Exception {
520     List<HRegionLocation> regions;
521     try (RegionLocator locator = systemUserConnection.getRegionLocator(TEST_TABLE.getTableName())) {
522       regions = locator.getAllRegionLocations();
523     }
524     HRegionLocation location = regions.get(0);
525     final HRegionInfo hri = location.getRegionInfo();
526     AccessTestAction action = new AccessTestAction() {
527       @Override
528       public Object run() throws Exception {
529         ACCESS_CONTROLLER.preRegionOffline(ObserverContext.createAndPrepare(CP_ENV, null), hri);
530         return null;
531       }
532     };
533 
534     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWNER);
535     verifyDenied(action, USER_CREATE, USER_RW, USER_RO, USER_NONE);
536   }
537 
538   @Test
539   public void testBalance() throws Exception {
540     AccessTestAction action = new AccessTestAction() {
541       @Override
542       public Object run() throws Exception {
543         ACCESS_CONTROLLER.preBalance(ObserverContext.createAndPrepare(CP_ENV, null));
544         return null;
545       }
546     };
547 
548     verifyAllowed(action, SUPERUSER, USER_ADMIN);
549     verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO, USER_NONE);
550   }
551 
552   @Test
553   public void testBalanceSwitch() throws Exception {
554     AccessTestAction action = new AccessTestAction() {
555       @Override
556       public Object run() throws Exception {
557         ACCESS_CONTROLLER.preBalanceSwitch(ObserverContext.createAndPrepare(CP_ENV, null), true);
558         return null;
559       }
560     };
561 
562     verifyAllowed(action, SUPERUSER, USER_ADMIN);
563     verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO, USER_NONE);
564   }
565 
566   @Test
567   public void testShutdown() throws Exception {
568     AccessTestAction action = new AccessTestAction() {
569       @Override
570       public Object run() throws Exception {
571         ACCESS_CONTROLLER.preShutdown(ObserverContext.createAndPrepare(CP_ENV, null));
572         return null;
573       }
574     };
575 
576     verifyAllowed(action, SUPERUSER, USER_ADMIN);
577     verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO, USER_NONE);
578   }
579 
580   @Test
581   public void testStopMaster() throws Exception {
582     AccessTestAction action = new AccessTestAction() {
583       @Override
584       public Object run() throws Exception {
585         ACCESS_CONTROLLER.preStopMaster(ObserverContext.createAndPrepare(CP_ENV, null));
586         return null;
587       }
588     };
589 
590     verifyAllowed(action, SUPERUSER, USER_ADMIN);
591     verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO, USER_NONE);
592   }
593 
594   private void verifyWrite(AccessTestAction action) throws Exception {
595     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE, USER_RW);
596     verifyDenied(action, USER_NONE, USER_RO);
597   }
598 
599   @Test
600   public void testSplit() throws Exception {
601     AccessTestAction action = new AccessTestAction() {
602       @Override
603       public Object run() throws Exception {
604         ACCESS_CONTROLLER.preSplit(ObserverContext.createAndPrepare(RCP_ENV, null));
605         return null;
606       }
607     };
608 
609     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWNER);
610     verifyDenied(action, USER_CREATE, USER_RW, USER_RO, USER_NONE);
611   }
612 
613   @Test
614   public void testSplitWithSplitRow() throws Exception {
615     AccessTestAction action = new AccessTestAction() {
616       @Override
617       public Object run() throws Exception {
618         ACCESS_CONTROLLER.preSplit(
619             ObserverContext.createAndPrepare(RCP_ENV, null),
620             TEST_ROW);
621         return null;
622       }
623     };
624 
625     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWNER);
626     verifyDenied(action, USER_CREATE, USER_RW, USER_RO, USER_NONE);
627   }
628 
629   @Test
630   public void testMergeRegions() throws Exception {
631     final List<HRegion> regions = TEST_UTIL.getHBaseCluster().findRegionsForTable(TEST_TABLE.getTableName());
632     assertTrue("not enough regions: " + regions.size(), regions.size() >= 2);
633 
634     AccessTestAction action = new AccessTestAction() {
635       @Override
636       public Object run() throws Exception {
637         ACCESS_CONTROLLER.preMerge(
638             ObserverContext.createAndPrepare(RSCP_ENV, null),
639             regions.get(0),regions.get(1));
640         return null;
641       }
642     };
643 
644     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWNER);
645     verifyDenied(action, USER_CREATE, USER_RW, USER_RO, USER_NONE);
646   }
647 
648   @Test
649   public void testFlush() throws Exception {
650     AccessTestAction action = new AccessTestAction() {
651       @Override
652       public Object run() throws Exception {
653         ACCESS_CONTROLLER.preFlush(ObserverContext.createAndPrepare(RCP_ENV, null));
654         return null;
655       }
656     };
657 
658     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE);
659     verifyDenied(action, USER_RW, USER_RO, USER_NONE);
660   }
661 
662   @Test
663   public void testCompact() throws Exception {
664     AccessTestAction action = new AccessTestAction() {
665       @Override
666       public Object run() throws Exception {
667         ACCESS_CONTROLLER.preCompact(ObserverContext.createAndPrepare(RCP_ENV, null), null, null,
668           ScanType.COMPACT_RETAIN_DELETES);
669         return null;
670       }
671     };
672 
673     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE);
674     verifyDenied(action, USER_RW, USER_RO, USER_NONE);
675   }
676 
677   private void verifyRead(AccessTestAction action) throws Exception {
678     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE, USER_RW, USER_RO);
679     verifyDenied(action, USER_NONE);
680   }
681 
682   private void verifyReadWrite(AccessTestAction action) throws Exception {
683     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE, USER_RW);
684     verifyDenied(action, USER_NONE, USER_RO);
685   }
686 
687   @Test
688   public void testRead() throws Exception {
689     // get action
690     AccessTestAction getAction = new AccessTestAction() {
691       @Override
692       public Object run() throws Exception {
693         Get g = new Get(TEST_ROW);
694         g.addFamily(TEST_FAMILY);
695         try(Connection conn = ConnectionFactory.createConnection(conf);
696             Table t = conn.getTable(TEST_TABLE.getTableName())) {
697           t.get(g);
698         }
699         return null;
700       }
701     };
702     verifyRead(getAction);
703 
704     // action for scanning
705     AccessTestAction scanAction = new AccessTestAction() {
706       @Override
707       public Object run() throws Exception {
708         Scan s = new Scan();
709         s.addFamily(TEST_FAMILY);
710 
711         try(Connection conn = ConnectionFactory.createConnection(conf);
712             Table t = conn.getTable(TEST_TABLE.getTableName())) {
713           ResultScanner scanner = t.getScanner(s);
714           try {
715             for (Result r = scanner.next(); r != null; r = scanner.next()) {
716               // do nothing
717             }
718           } catch (IOException e) {
719           } finally {
720             scanner.close();
721           }
722         }
723         return null;
724       }
725     };
726     verifyRead(scanAction);
727   }
728 
729   @Test
730   // test put, delete, increment
731   public void testWrite() throws Exception {
732     // put action
733     AccessTestAction putAction = new AccessTestAction() {
734       @Override
735       public Object run() throws Exception {
736         Put p = new Put(TEST_ROW);
737         p.add(TEST_FAMILY, TEST_QUALIFIER, Bytes.toBytes(1));
738         try(Connection conn = ConnectionFactory.createConnection(conf);
739             Table t = conn.getTable(TEST_TABLE.getTableName())) {
740           t.put(p);
741         }
742         return null;
743       }
744     };
745     verifyWrite(putAction);
746 
747     // delete action
748     AccessTestAction deleteAction = new AccessTestAction() {
749       @Override
750       public Object run() throws Exception {
751         Delete d = new Delete(TEST_ROW);
752         d.deleteFamily(TEST_FAMILY);
753         try(Connection conn = ConnectionFactory.createConnection(conf);
754             Table t = conn.getTable(TEST_TABLE.getTableName())) {
755           t.delete(d);
756         }
757         return null;
758       }
759     };
760     verifyWrite(deleteAction);
761 
762     // increment action
763     AccessTestAction incrementAction = new AccessTestAction() {
764       @Override
765       public Object run() throws Exception {
766         Increment inc = new Increment(TEST_ROW);
767         inc.addColumn(TEST_FAMILY, TEST_QUALIFIER, 1);
768         try(Connection conn = ConnectionFactory.createConnection(conf);
769             Table t = conn.getTable(TEST_TABLE.getTableName())) {
770           t.increment(inc);
771         }
772         return null;
773       }
774     };
775     verifyWrite(incrementAction);
776   }
777 
778   @Test
779   public void testReadWrite() throws Exception {
780     // action for checkAndDelete
781     AccessTestAction checkAndDeleteAction = new AccessTestAction() {
782       @Override
783       public Object run() throws Exception {
784         Delete d = new Delete(TEST_ROW);
785         d.deleteFamily(TEST_FAMILY);
786         try(Connection conn = ConnectionFactory.createConnection(conf);
787             Table t = conn.getTable(TEST_TABLE.getTableName())) {
788           t.checkAndDelete(TEST_ROW, TEST_FAMILY, TEST_QUALIFIER,
789               Bytes.toBytes("test_value"), d);
790         }
791         return null;
792       }
793     };
794     verifyReadWrite(checkAndDeleteAction);
795 
796     // action for checkAndPut()
797     AccessTestAction checkAndPut = new AccessTestAction() {
798       @Override
799       public Object run() throws Exception {
800         Put p = new Put(TEST_ROW);
801         p.add(TEST_FAMILY, TEST_QUALIFIER, Bytes.toBytes(1));
802         try(Connection conn = ConnectionFactory.createConnection(conf);
803             Table t = conn.getTable(TEST_TABLE.getTableName())) {
804           t.checkAndPut(TEST_ROW, TEST_FAMILY, TEST_QUALIFIER,
805               Bytes.toBytes("test_value"), p);
806         }
807         return null;
808       }
809     };
810     verifyReadWrite(checkAndPut);
811   }
812 
813   @Test
814   public void testBulkLoad() throws Exception {
815     FileSystem fs = TEST_UTIL.getTestFileSystem();
816     final Path dir = TEST_UTIL.getDataTestDirOnTestFS("testBulkLoad");
817     fs.mkdirs(dir);
818     //need to make it globally writable
819     //so users creating HFiles have write permissions
820     fs.setPermission(dir, FsPermission.valueOf("-rwxrwxrwx"));
821 
822     AccessTestAction bulkLoadAction = new AccessTestAction() {
823       @Override
824       public Object run() throws Exception {
825         int numRows = 3;
826 
827         //Making the assumption that the test table won't split between the range
828         byte[][][] hfileRanges = {{{(byte)0}, {(byte)9}}};
829 
830         Path bulkLoadBasePath = new Path(dir, new Path(User.getCurrent().getName()));
831         new BulkLoadHelper(bulkLoadBasePath)
832             .bulkLoadHFile(TEST_TABLE.getTableName(), TEST_FAMILY, TEST_QUALIFIER, hfileRanges, numRows);
833 
834         return null;
835       }
836     };
837 
838     // User performing bulk loads must have privilege to read table metadata
839     // (ADMIN or CREATE)
840     verifyAllowed(bulkLoadAction, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE);
841     verifyDenied(bulkLoadAction, USER_RW, USER_NONE, USER_RO);
842 
843     // Reinit after the bulk upload
844     TEST_UTIL.getHBaseAdmin().disableTable(TEST_TABLE.getTableName());
845     TEST_UTIL.getHBaseAdmin().enableTable(TEST_TABLE.getTableName());
846   }
847 
848   public class BulkLoadHelper {
849     private final FileSystem fs;
850     private final Path loadPath;
851     private final Configuration conf;
852 
853     public BulkLoadHelper(Path loadPath) throws IOException {
854       fs = TEST_UTIL.getTestFileSystem();
855       conf = TEST_UTIL.getConfiguration();
856       loadPath = loadPath.makeQualified(fs);
857       this.loadPath = loadPath;
858     }
859 
860     private void createHFile(Path path,
861         byte[] family, byte[] qualifier,
862         byte[] startKey, byte[] endKey, int numRows) throws IOException {
863 
864       HFile.Writer writer = null;
865       long now = System.currentTimeMillis();
866       try {
867         HFileContext context = new HFileContextBuilder().build();
868         writer = HFile.getWriterFactory(conf, new CacheConfig(conf))
869             .withPath(fs, path)
870             .withFileContext(context)
871             .create();
872         // subtract 2 since numRows doesn't include boundary keys
873         for (byte[] key : Bytes.iterateOnSplits(startKey, endKey, true, numRows-2)) {
874           KeyValue kv = new KeyValue(key, family, qualifier, now, key);
875           writer.append(kv);
876         }
877       } finally {
878         if(writer != null)
879           writer.close();
880       }
881     }
882 
883     private void bulkLoadHFile(
884         TableName tableName,
885         byte[] family,
886         byte[] qualifier,
887         byte[][][] hfileRanges,
888         int numRowsPerRange) throws Exception {
889 
890       Path familyDir = new Path(loadPath, Bytes.toString(family));
891       fs.mkdirs(familyDir);
892       int hfileIdx = 0;
893       for (byte[][] range : hfileRanges) {
894         byte[] from = range[0];
895         byte[] to = range[1];
896         createHFile(new Path(familyDir, "hfile_"+(hfileIdx++)),
897             family, qualifier, from, to, numRowsPerRange);
898       }
899       //set global read so RegionServer can move it
900       setPermission(loadPath, FsPermission.valueOf("-rwxrwxrwx"));
901 
902       try (Connection conn = ConnectionFactory.createConnection(conf);
903            HTable table = (HTable)conn.getTable(tableName)) {
904         TEST_UTIL.waitUntilAllRegionsAssigned(tableName);
905         LoadIncrementalHFiles loader = new LoadIncrementalHFiles(conf);
906         loader.doBulkLoad(loadPath, table);
907       }
908     }
909 
910     public void setPermission(Path dir, FsPermission perm) throws IOException {
911       if(!fs.getFileStatus(dir).isDirectory()) {
912         fs.setPermission(dir,perm);
913       }
914       else {
915         for(FileStatus el : fs.listStatus(dir)) {
916           fs.setPermission(el.getPath(), perm);
917           setPermission(el.getPath() , perm);
918         }
919       }
920     }
921   }
922 
923   @Test
924   public void testAppend() throws Exception {
925 
926     AccessTestAction appendAction = new AccessTestAction() {
927       @Override
928       public Object run() throws Exception {
929         byte[] row = TEST_ROW;
930         byte[] qualifier = TEST_QUALIFIER;
931         Put put = new Put(row);
932         put.add(TEST_FAMILY, qualifier, Bytes.toBytes(1));
933         Append append = new Append(row);
934         append.add(TEST_FAMILY, qualifier, Bytes.toBytes(2));
935         try(Connection conn = ConnectionFactory.createConnection(conf);
936             Table t = conn.getTable(TEST_TABLE.getTableName())) {
937           t.put(put);
938           t.append(append);
939         }
940         return null;
941       }
942     };
943 
944     verifyAllowed(appendAction, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE, USER_RW);
945     verifyDenied(appendAction, USER_RO, USER_NONE);
946   }
947 
948   @Test
949   public void testGrantRevoke() throws Exception {
950     AccessTestAction grantAction = new AccessTestAction() {
951       @Override
952       public Object run() throws Exception {
953         try(Connection conn = ConnectionFactory.createConnection(conf);
954             Table acl = conn.getTable(AccessControlLists.ACL_TABLE_NAME)) {
955           BlockingRpcChannel service = acl.coprocessorService(TEST_TABLE.getTableName().getName());
956           AccessControlService.BlockingInterface protocol =
957             AccessControlService.newBlockingStub(service);
958           ProtobufUtil.grant(protocol, USER_RO.getShortName(), TEST_TABLE.getTableName(),
959             TEST_FAMILY, null, Action.READ);
960         }
961         return null;
962       }
963     };
964 
965     AccessTestAction revokeAction = new AccessTestAction() {
966       @Override
967       public Object run() throws Exception {
968         try(Connection conn = ConnectionFactory.createConnection(conf);
969             Table acl = conn.getTable(AccessControlLists.ACL_TABLE_NAME)) {
970           BlockingRpcChannel service = acl.coprocessorService(TEST_TABLE.getTableName().getName());
971           AccessControlService.BlockingInterface protocol =
972             AccessControlService.newBlockingStub(service);
973           ProtobufUtil.revoke(protocol, USER_RO.getShortName(), TEST_TABLE.getTableName(),
974               TEST_FAMILY, null, Action.READ);
975         }
976         return null;
977       }
978     };
979 
980     AccessTestAction getTablePermissionsAction = new AccessTestAction() {
981       @Override
982       public Object run() throws Exception {
983         try(Connection conn = ConnectionFactory.createConnection(conf);
984             Table acl = conn.getTable(AccessControlLists.ACL_TABLE_NAME)) {
985           BlockingRpcChannel service = acl.coprocessorService(TEST_TABLE.getTableName().getName());
986           AccessControlService.BlockingInterface protocol =
987             AccessControlService.newBlockingStub(service);
988           ProtobufUtil.getUserPermissions(protocol, TEST_TABLE.getTableName());
989         }
990         return null;
991       }
992     };
993 
994     AccessTestAction getGlobalPermissionsAction = new AccessTestAction() {
995       @Override
996       public Object run() throws Exception {
997         try(Connection conn = ConnectionFactory.createConnection(conf);
998             Table acl = conn.getTable(AccessControlLists.ACL_TABLE_NAME)) {
999           BlockingRpcChannel service = acl.coprocessorService(HConstants.EMPTY_START_ROW);
1000           AccessControlService.BlockingInterface protocol =
1001             AccessControlService.newBlockingStub(service);
1002           ProtobufUtil.getUserPermissions(protocol);
1003         }
1004         return null;
1005       }
1006     };
1007 
1008     verifyAllowed(grantAction, SUPERUSER, USER_ADMIN, USER_OWNER);
1009     verifyDenied(grantAction, USER_CREATE, USER_RW, USER_RO, USER_NONE);
1010 
1011     verifyAllowed(revokeAction, SUPERUSER, USER_ADMIN, USER_OWNER);
1012     verifyDenied(revokeAction, USER_CREATE, USER_RW, USER_RO, USER_NONE);
1013 
1014     verifyAllowed(getTablePermissionsAction, SUPERUSER, USER_ADMIN, USER_OWNER);
1015     verifyDenied(getTablePermissionsAction, USER_CREATE, USER_RW, USER_RO, USER_NONE);
1016 
1017     verifyAllowed(getGlobalPermissionsAction, SUPERUSER, USER_ADMIN);
1018     verifyDenied(getGlobalPermissionsAction, USER_CREATE,
1019         USER_OWNER, USER_RW, USER_RO, USER_NONE);
1020   }
1021 
1022   @Test
1023   public void testPostGrantRevoke() throws Exception {
1024     final TableName tableName =
1025         TableName.valueOf("TempTable");
1026     final byte[] family1 = Bytes.toBytes("f1");
1027     final byte[] family2 = Bytes.toBytes("f2");
1028     final byte[] qualifier = Bytes.toBytes("q");
1029 
1030     // create table
1031     Admin admin = TEST_UTIL.getHBaseAdmin();
1032     if (admin.tableExists(tableName)) {
1033       deleteTable(TEST_UTIL, tableName);
1034     }
1035     HTableDescriptor htd = new HTableDescriptor(tableName);
1036     htd.addFamily(new HColumnDescriptor(family1));
1037     htd.addFamily(new HColumnDescriptor(family2));
1038     createTable(TEST_UTIL, htd);
1039 
1040     // create temp users
1041     User tblUser = User
1042         .createUserForTesting(TEST_UTIL.getConfiguration(), "tbluser", new String[0]);
1043     User gblUser = User
1044         .createUserForTesting(TEST_UTIL.getConfiguration(), "gbluser", new String[0]);
1045 
1046     // prepare actions:
1047     AccessTestAction putActionAll = new AccessTestAction() {
1048       @Override
1049       public Object run() throws Exception {
1050         Put p = new Put(Bytes.toBytes("a"));
1051         p.add(family1, qualifier, Bytes.toBytes("v1"));
1052         p.add(family2, qualifier, Bytes.toBytes("v2"));
1053         try(Connection conn = ConnectionFactory.createConnection(conf);
1054             Table t = conn.getTable(tableName)) {
1055           t.put(p);
1056         }
1057         return null;
1058       }
1059     };
1060 
1061     AccessTestAction putAction1 = new AccessTestAction() {
1062       @Override
1063       public Object run() throws Exception {
1064         Put p = new Put(Bytes.toBytes("a"));
1065         p.add(family1, qualifier, Bytes.toBytes("v1"));
1066         try(Connection conn = ConnectionFactory.createConnection(conf);
1067             Table t = conn.getTable(tableName)) {
1068           t.put(p);
1069         }
1070         return null;
1071       }
1072     };
1073 
1074     AccessTestAction putAction2 = new AccessTestAction() {
1075       @Override
1076       public Object run() throws Exception {
1077         Put p = new Put(Bytes.toBytes("a"));
1078         p.add(family2, qualifier, Bytes.toBytes("v2"));
1079         try(Connection conn = ConnectionFactory.createConnection(conf);
1080             Table t = conn.getTable(tableName)) {
1081           t.put(p);
1082         }
1083         return null;
1084       }
1085     };
1086 
1087     AccessTestAction getActionAll = new AccessTestAction() {
1088       @Override
1089       public Object run() throws Exception {
1090         Get g = new Get(TEST_ROW);
1091         g.addFamily(family1);
1092         g.addFamily(family2);
1093         try(Connection conn = ConnectionFactory.createConnection(conf);
1094             Table t = conn.getTable(tableName)) {
1095           t.get(g);
1096         }
1097         return null;
1098       }
1099     };
1100 
1101     AccessTestAction getAction1 = new AccessTestAction() {
1102       @Override
1103       public Object run() throws Exception {
1104         Get g = new Get(TEST_ROW);
1105         g.addFamily(family1);
1106         try(Connection conn = ConnectionFactory.createConnection(conf);
1107             Table t = conn.getTable(tableName)) {
1108           t.get(g);
1109         }
1110         return null;
1111       }
1112     };
1113 
1114     AccessTestAction getAction2 = new AccessTestAction() {
1115       @Override
1116       public Object run() throws Exception {
1117         Get g = new Get(TEST_ROW);
1118         g.addFamily(family2);
1119         try(Connection conn = ConnectionFactory.createConnection(conf);
1120             Table t = conn.getTable(tableName)) {
1121           t.get(g);
1122         }
1123         return null;
1124       }
1125     };
1126 
1127     AccessTestAction deleteActionAll = new AccessTestAction() {
1128       @Override
1129       public Object run() throws Exception {
1130         Delete d = new Delete(TEST_ROW);
1131         d.deleteFamily(family1);
1132         d.deleteFamily(family2);
1133         try(Connection conn = ConnectionFactory.createConnection(conf);
1134             Table t = conn.getTable(tableName)) {
1135           t.delete(d);
1136         }
1137         return null;
1138       }
1139     };
1140 
1141     AccessTestAction deleteAction1 = new AccessTestAction() {
1142       @Override
1143       public Object run() throws Exception {
1144         Delete d = new Delete(TEST_ROW);
1145         d.deleteFamily(family1);
1146         try(Connection conn = ConnectionFactory.createConnection(conf);
1147             Table t = conn.getTable(tableName)) {
1148           t.delete(d);
1149         }
1150         return null;
1151       }
1152     };
1153 
1154     AccessTestAction deleteAction2 = new AccessTestAction() {
1155       @Override
1156       public Object run() throws Exception {
1157         Delete d = new Delete(TEST_ROW);
1158         d.deleteFamily(family2);
1159         try(Connection conn = ConnectionFactory.createConnection(conf);
1160             Table t = conn.getTable(tableName)) {
1161           t.delete(d);
1162         }
1163         return null;
1164       }
1165     };
1166 
1167     // initial check:
1168     verifyDenied(tblUser, getActionAll, getAction1, getAction2);
1169     verifyDenied(tblUser, putActionAll, putAction1, putAction2);
1170     verifyDenied(tblUser, deleteActionAll, deleteAction1, deleteAction2);
1171 
1172     verifyDenied(gblUser, getActionAll, getAction1, getAction2);
1173     verifyDenied(gblUser, putActionAll, putAction1, putAction2);
1174     verifyDenied(gblUser, deleteActionAll, deleteAction1, deleteAction2);
1175 
1176     // grant table read permission
1177     grantGlobal(TEST_UTIL, gblUser.getShortName(),
1178       Permission.Action.READ);
1179     grantOnTable(TEST_UTIL, tblUser.getShortName(),
1180       tableName, null, null,
1181       Permission.Action.READ);
1182 
1183     // check
1184     verifyAllowed(tblUser, getActionAll, getAction1, getAction2);
1185     verifyDenied(tblUser, putActionAll, putAction1, putAction2);
1186     verifyDenied(tblUser, deleteActionAll, deleteAction1, deleteAction2);
1187 
1188     verifyAllowed(gblUser, getActionAll, getAction1, getAction2);
1189     verifyDenied(gblUser, putActionAll, putAction1, putAction2);
1190     verifyDenied(gblUser, deleteActionAll, deleteAction1, deleteAction2);
1191 
1192     // grant table write permission while revoking read permissions
1193     grantGlobal(TEST_UTIL, gblUser.getShortName(),
1194       Permission.Action.WRITE);
1195     grantOnTable(TEST_UTIL, tblUser.getShortName(),
1196       tableName, null, null,
1197       Permission.Action.WRITE);
1198 
1199     verifyDenied(tblUser, getActionAll, getAction1, getAction2);
1200     verifyAllowed(tblUser, putActionAll, putAction1, putAction2);
1201     verifyAllowed(tblUser, deleteActionAll, deleteAction1, deleteAction2);
1202 
1203     verifyDenied(gblUser, getActionAll, getAction1, getAction2);
1204     verifyAllowed(gblUser, putActionAll, putAction1, putAction2);
1205     verifyAllowed(gblUser, deleteActionAll, deleteAction1, deleteAction2);
1206 
1207     // revoke table permissions
1208     revokeGlobal(TEST_UTIL, gblUser.getShortName());
1209     revokeFromTable(TEST_UTIL, tblUser.getShortName(),
1210       tableName, null, null);
1211 
1212     verifyDenied(tblUser, getActionAll, getAction1, getAction2);
1213     verifyDenied(tblUser, putActionAll, putAction1, putAction2);
1214     verifyDenied(tblUser, deleteActionAll, deleteAction1, deleteAction2);
1215 
1216     verifyDenied(gblUser, getActionAll, getAction1, getAction2);
1217     verifyDenied(gblUser, putActionAll, putAction1, putAction2);
1218     verifyDenied(gblUser, deleteActionAll, deleteAction1, deleteAction2);
1219 
1220     // grant column family read permission
1221     grantGlobal(TEST_UTIL, gblUser.getShortName(),
1222       Permission.Action.READ);
1223     grantOnTable(TEST_UTIL, tblUser.getShortName(),
1224       tableName, family1, null, Permission.Action.READ);
1225 
1226     // Access should be denied for family2
1227     verifyAllowed(tblUser, getActionAll, getAction1);
1228     verifyDenied(tblUser, getAction2);
1229     verifyDenied(tblUser, putActionAll, putAction1, putAction2);
1230     verifyDenied(tblUser, deleteActionAll, deleteAction1, deleteAction2);
1231 
1232     verifyAllowed(gblUser, getActionAll, getAction1, getAction2);
1233     verifyDenied(gblUser, putActionAll, putAction1, putAction2);
1234     verifyDenied(gblUser, deleteActionAll, deleteAction1, deleteAction2);
1235 
1236     // grant column family write permission
1237     grantGlobal(TEST_UTIL, gblUser.getShortName(),
1238       Permission.Action.WRITE);
1239     grantOnTable(TEST_UTIL, tblUser.getShortName(),
1240       tableName, family2, null, Permission.Action.WRITE);
1241 
1242     // READ from family1, WRITE to family2 are allowed
1243     verifyAllowed(tblUser, getActionAll, getAction1);
1244     verifyAllowed(tblUser, putAction2, deleteAction2);
1245     verifyDenied(tblUser, getAction2);
1246     verifyDenied(tblUser, putActionAll, putAction1);
1247     verifyDenied(tblUser, deleteActionAll, deleteAction1);
1248 
1249     verifyDenied(gblUser, getActionAll, getAction1, getAction2);
1250     verifyAllowed(gblUser, putActionAll, putAction1, putAction2);
1251     verifyAllowed(gblUser, deleteActionAll, deleteAction1, deleteAction2);
1252 
1253     // revoke column family permission
1254     revokeGlobal(TEST_UTIL, gblUser.getShortName());
1255     revokeFromTable(TEST_UTIL, tblUser.getShortName(), tableName, family2, null);
1256 
1257     // Revoke on family2 should not have impact on family1 permissions
1258     verifyAllowed(tblUser, getActionAll, getAction1);
1259     verifyDenied(tblUser, getAction2);
1260     verifyDenied(tblUser, putActionAll, putAction1, putAction2);
1261     verifyDenied(tblUser, deleteActionAll, deleteAction1, deleteAction2);
1262 
1263     // Should not have access as global permissions are completely revoked
1264     verifyDenied(gblUser, getActionAll, getAction1, getAction2);
1265     verifyDenied(gblUser, putActionAll, putAction1, putAction2);
1266     verifyDenied(gblUser, deleteActionAll, deleteAction1, deleteAction2);
1267 
1268     // delete table
1269     deleteTable(TEST_UTIL, tableName);
1270   }
1271 
1272   private boolean hasFoundUserPermission(UserPermission userPermission, List<UserPermission> perms) {
1273     return perms.contains(userPermission);
1274   }
1275 
1276   @Test
1277   public void testPostGrantRevokeAtQualifierLevel() throws Exception {
1278     final TableName tableName =
1279         TableName.valueOf("testGrantRevokeAtQualifierLevel");
1280     final byte[] family1 = Bytes.toBytes("f1");
1281     final byte[] family2 = Bytes.toBytes("f2");
1282     final byte[] qualifier = Bytes.toBytes("q");
1283 
1284     // create table
1285     Admin admin = TEST_UTIL.getHBaseAdmin();
1286     if (admin.tableExists(tableName)) {
1287       deleteTable(TEST_UTIL, tableName);
1288     }
1289     HTableDescriptor htd = new HTableDescriptor(tableName);
1290     htd.addFamily(new HColumnDescriptor(family1));
1291     htd.addFamily(new HColumnDescriptor(family2));
1292     createTable(TEST_UTIL, htd);
1293 
1294     // create temp users
1295     User user = User.createUserForTesting(TEST_UTIL.getConfiguration(), "user", new String[0]);
1296 
1297     AccessTestAction getQualifierAction = new AccessTestAction() {
1298       @Override
1299       public Object run() throws Exception {
1300         Get g = new Get(TEST_ROW);
1301         g.addColumn(family1, qualifier);
1302         try(Connection conn = ConnectionFactory.createConnection(conf);
1303             Table t = conn.getTable(tableName)) {
1304           t.get(g);
1305         }
1306         return null;
1307       }
1308     };
1309 
1310     AccessTestAction putQualifierAction = new AccessTestAction() {
1311       @Override
1312       public Object run() throws Exception {
1313         Put p = new Put(TEST_ROW);
1314         p.add(family1, qualifier, Bytes.toBytes("v1"));
1315         try(Connection conn = ConnectionFactory.createConnection(conf);
1316             Table t = conn.getTable(tableName)) {
1317           t.put(p);
1318         }
1319         return null;
1320       }
1321     };
1322 
1323     AccessTestAction deleteQualifierAction = new AccessTestAction() {
1324       @Override
1325       public Object run() throws Exception {
1326         Delete d = new Delete(TEST_ROW);
1327         d.deleteColumn(family1, qualifier);
1328         // d.deleteFamily(family1);
1329         try(Connection conn = ConnectionFactory.createConnection(conf);
1330             Table t = conn.getTable(tableName)) {
1331           t.delete(d);
1332         }
1333         return null;
1334       }
1335     };
1336 
1337     revokeFromTable(TEST_UTIL, user.getShortName(), tableName, family1, null);
1338 
1339     verifyDenied(user, getQualifierAction);
1340     verifyDenied(user, putQualifierAction);
1341     verifyDenied(user, deleteQualifierAction);
1342 
1343     grantOnTable(TEST_UTIL, user.getShortName(),
1344       tableName, family1, qualifier,
1345       Permission.Action.READ);
1346 
1347     verifyAllowed(user, getQualifierAction);
1348     verifyDenied(user, putQualifierAction);
1349     verifyDenied(user, deleteQualifierAction);
1350 
1351     // only grant write permission
1352     // TODO: comment this portion after HBASE-3583
1353     grantOnTable(TEST_UTIL, user.getShortName(),
1354       tableName, family1, qualifier,
1355       Permission.Action.WRITE);
1356 
1357     verifyDenied(user, getQualifierAction);
1358     verifyAllowed(user, putQualifierAction);
1359     verifyAllowed(user, deleteQualifierAction);
1360 
1361     // grant both read and write permission
1362     grantOnTable(TEST_UTIL, user.getShortName(),
1363       tableName, family1, qualifier,
1364       Permission.Action.READ, Permission.Action.WRITE);
1365 
1366     verifyAllowed(user, getQualifierAction);
1367     verifyAllowed(user, putQualifierAction);
1368     verifyAllowed(user, deleteQualifierAction);
1369 
1370     // revoke family level permission won't impact column level
1371     revokeFromTable(TEST_UTIL, user.getShortName(),
1372       tableName, family1, qualifier);
1373 
1374     verifyDenied(user, getQualifierAction);
1375     verifyDenied(user, putQualifierAction);
1376     verifyDenied(user, deleteQualifierAction);
1377 
1378     // delete table
1379     deleteTable(TEST_UTIL, tableName);
1380   }
1381 
1382   @Test
1383   public void testPermissionList() throws Exception {
1384     final TableName tableName =
1385         TableName.valueOf("testPermissionList");
1386     final byte[] family1 = Bytes.toBytes("f1");
1387     final byte[] family2 = Bytes.toBytes("f2");
1388     final byte[] qualifier = Bytes.toBytes("q");
1389 
1390     // create table
1391     Admin admin = TEST_UTIL.getHBaseAdmin();
1392     if (admin.tableExists(tableName)) {
1393       deleteTable(TEST_UTIL, tableName);
1394     }
1395     HTableDescriptor htd = new HTableDescriptor(tableName);
1396     htd.addFamily(new HColumnDescriptor(family1));
1397     htd.addFamily(new HColumnDescriptor(family2));
1398     htd.setOwner(USER_OWNER);
1399     createTable(TEST_UTIL, htd);
1400 
1401     List<UserPermission> perms;
1402 
1403     Table acl = systemUserConnection.getTable(AccessControlLists.ACL_TABLE_NAME);
1404     try {
1405       BlockingRpcChannel service = acl.coprocessorService(tableName.getName());
1406       AccessControlService.BlockingInterface protocol =
1407         AccessControlService.newBlockingStub(service);
1408       perms = ProtobufUtil.getUserPermissions(protocol, tableName);
1409     } finally {
1410       acl.close();
1411     }
1412 
1413     UserPermission ownerperm = new UserPermission(
1414       Bytes.toBytes(USER_OWNER.getName()), tableName, null, Action.values());
1415     assertTrue("Owner should have all permissions on table",
1416         hasFoundUserPermission(ownerperm, perms));
1417 
1418     User user = User.createUserForTesting(TEST_UTIL.getConfiguration(), "user", new String[0]);
1419     byte[] userName = Bytes.toBytes(user.getShortName());
1420 
1421     UserPermission up = new UserPermission(userName,
1422       tableName, family1, qualifier, Permission.Action.READ);
1423     assertFalse("User should not be granted permission: " + up.toString(),
1424       hasFoundUserPermission(up, perms));
1425 
1426     // grant read permission
1427     grantOnTable(TEST_UTIL, user.getShortName(),
1428       tableName, family1, qualifier, Permission.Action.READ);
1429 
1430     acl = systemUserConnection.getTable(AccessControlLists.ACL_TABLE_NAME);
1431     try {
1432       BlockingRpcChannel service = acl.coprocessorService(tableName.getName());
1433       AccessControlService.BlockingInterface protocol =
1434         AccessControlService.newBlockingStub(service);
1435       perms = ProtobufUtil.getUserPermissions(protocol, tableName);
1436     } finally {
1437       acl.close();
1438     }
1439 
1440     UserPermission upToVerify = new UserPermission(
1441       userName, tableName, family1, qualifier, Permission.Action.READ);
1442     assertTrue("User should be granted permission: " + upToVerify.toString(),
1443       hasFoundUserPermission(upToVerify, perms));
1444 
1445     upToVerify = new UserPermission(
1446       userName, tableName, family1, qualifier, Permission.Action.WRITE);
1447     assertFalse("User should not be granted permission: " + upToVerify.toString(),
1448       hasFoundUserPermission(upToVerify, perms));
1449 
1450     // grant read+write
1451     grantOnTable(TEST_UTIL, user.getShortName(),
1452       tableName, family1, qualifier,
1453       Permission.Action.WRITE, Permission.Action.READ);
1454 
1455     acl = systemUserConnection.getTable(AccessControlLists.ACL_TABLE_NAME);
1456     try {
1457       BlockingRpcChannel service = acl.coprocessorService(tableName.getName());
1458       AccessControlService.BlockingInterface protocol =
1459         AccessControlService.newBlockingStub(service);
1460       perms = ProtobufUtil.getUserPermissions(protocol, tableName);
1461     } finally {
1462       acl.close();
1463     }
1464 
1465     upToVerify = new UserPermission(userName, tableName, family1,
1466       qualifier, Permission.Action.WRITE, Permission.Action.READ);
1467     assertTrue("User should be granted permission: " + upToVerify.toString(),
1468       hasFoundUserPermission(upToVerify, perms));
1469 
1470     // revoke
1471     revokeFromTable(TEST_UTIL, user.getShortName(), tableName, family1, qualifier,
1472       Permission.Action.WRITE, Permission.Action.READ);
1473 
1474     acl = systemUserConnection.getTable(AccessControlLists.ACL_TABLE_NAME);
1475     try {
1476       BlockingRpcChannel service = acl.coprocessorService(tableName.getName());
1477       AccessControlService.BlockingInterface protocol =
1478         AccessControlService.newBlockingStub(service);
1479       perms = ProtobufUtil.getUserPermissions(protocol, tableName);
1480     } finally {
1481       acl.close();
1482     }
1483 
1484     assertFalse("User should not be granted permission: " + upToVerify.toString(),
1485         hasFoundUserPermission(upToVerify, perms));
1486 
1487     // disable table before modification
1488     admin.disableTable(tableName);
1489 
1490     User newOwner = User.createUserForTesting(conf, "new_owner", new String[] {});
1491     htd.setOwner(newOwner);
1492     admin.modifyTable(tableName, htd);
1493 
1494     acl = systemUserConnection.getTable(AccessControlLists.ACL_TABLE_NAME);
1495     try {
1496       BlockingRpcChannel service = acl.coprocessorService(tableName.getName());
1497       AccessControlService.BlockingInterface protocol =
1498         AccessControlService.newBlockingStub(service);
1499       perms = ProtobufUtil.getUserPermissions(protocol, tableName);
1500     } finally {
1501       acl.close();
1502     }
1503 
1504     UserPermission newOwnerperm = new UserPermission(
1505       Bytes.toBytes(newOwner.getName()), tableName, null, Action.values());
1506     assertTrue("New owner should have all permissions on table",
1507         hasFoundUserPermission(newOwnerperm, perms));
1508 
1509     // delete table
1510     deleteTable(TEST_UTIL, tableName);
1511   }
1512 
1513   @Test
1514   public void testGlobalPermissionList() throws Exception {
1515     List<UserPermission> perms;
1516     Table acl = systemUserConnection.getTable(AccessControlLists.ACL_TABLE_NAME);
1517     try {
1518       BlockingRpcChannel service = acl.coprocessorService(HConstants.EMPTY_START_ROW);
1519       AccessControlService.BlockingInterface protocol =
1520         AccessControlService.newBlockingStub(service);
1521       perms = ProtobufUtil.getUserPermissions(protocol);
1522     } finally {
1523       acl.close();
1524     }
1525     UserPermission adminPerm = new UserPermission(Bytes.toBytes(USER_ADMIN.getShortName()),
1526       AccessControlLists.ACL_TABLE_NAME, null, null, Bytes.toBytes("ACRW"));
1527     assertTrue("Only user admin has permission on table _acl_ per setup",
1528       perms.size() == 1 && hasFoundUserPermission(adminPerm, perms));
1529   }
1530 
1531   /** global operations */
1532   private void verifyGlobal(AccessTestAction action) throws Exception {
1533     verifyAllowed(action, SUPERUSER);
1534 
1535     verifyDenied(action, USER_CREATE, USER_RW, USER_NONE, USER_RO);
1536   }
1537 
1538   @Test
1539   public void testCheckPermissions() throws Exception {
1540     // --------------------------------------
1541     // test global permissions
1542     AccessTestAction globalAdmin = new AccessTestAction() {
1543       @Override
1544       public Void run() throws Exception {
1545         checkGlobalPerms(TEST_UTIL, Permission.Action.ADMIN);
1546         return null;
1547       }
1548     };
1549     // verify that only superuser can admin
1550     verifyGlobal(globalAdmin);
1551 
1552     // --------------------------------------
1553     // test multiple permissions
1554     AccessTestAction globalReadWrite = new AccessTestAction() {
1555       @Override
1556       public Void run() throws Exception {
1557         checkGlobalPerms(TEST_UTIL, Permission.Action.READ, Permission.Action.WRITE);
1558         return null;
1559       }
1560     };
1561 
1562     verifyGlobal(globalReadWrite);
1563 
1564     // --------------------------------------
1565     // table/column/qualifier level permissions
1566     final byte[] TEST_Q1 = Bytes.toBytes("q1");
1567     final byte[] TEST_Q2 = Bytes.toBytes("q2");
1568 
1569     User userTable = User.createUserForTesting(conf, "user_check_perms_table", new String[0]);
1570     User userColumn = User.createUserForTesting(conf, "user_check_perms_family", new String[0]);
1571     User userQualifier = User.createUserForTesting(conf, "user_check_perms_q", new String[0]);
1572 
1573     grantOnTable(TEST_UTIL, userTable.getShortName(),
1574       TEST_TABLE.getTableName(), null, null,
1575       Permission.Action.READ);
1576     grantOnTable(TEST_UTIL, userColumn.getShortName(),
1577       TEST_TABLE.getTableName(), TEST_FAMILY, null,
1578       Permission.Action.READ);
1579     grantOnTable(TEST_UTIL, userQualifier.getShortName(),
1580       TEST_TABLE.getTableName(), TEST_FAMILY, TEST_Q1,
1581       Permission.Action.READ);
1582 
1583     AccessTestAction tableRead = new AccessTestAction() {
1584       @Override
1585       public Void run() throws Exception {
1586         checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), null, null,
1587           Permission.Action.READ);
1588         return null;
1589       }
1590     };
1591 
1592     AccessTestAction columnRead = new AccessTestAction() {
1593       @Override
1594       public Void run() throws Exception {
1595         checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), TEST_FAMILY, null,
1596           Permission.Action.READ);
1597         return null;
1598       }
1599     };
1600 
1601     AccessTestAction qualifierRead = new AccessTestAction() {
1602       @Override
1603       public Void run() throws Exception {
1604         checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), TEST_FAMILY, TEST_Q1,
1605           Permission.Action.READ);
1606         return null;
1607       }
1608     };
1609 
1610     AccessTestAction multiQualifierRead = new AccessTestAction() {
1611       @Override
1612       public Void run() throws Exception {
1613         checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), new Permission[] {
1614             new TablePermission(TEST_TABLE.getTableName(), TEST_FAMILY, TEST_Q1,
1615               Permission.Action.READ),
1616             new TablePermission(TEST_TABLE.getTableName(), TEST_FAMILY, TEST_Q2,
1617               Permission.Action.READ), });
1618         return null;
1619       }
1620     };
1621 
1622     AccessTestAction globalAndTableRead = new AccessTestAction() {
1623       @Override
1624       public Void run() throws Exception {
1625         checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(),
1626           new Permission[] { new Permission(Permission.Action.READ),
1627             new TablePermission(TEST_TABLE.getTableName(), null, (byte[]) null,
1628             Permission.Action.READ), });
1629         return null;
1630       }
1631     };
1632 
1633     AccessTestAction noCheck = new AccessTestAction() {
1634       @Override
1635       public Void run() throws Exception {
1636         checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), new Permission[0]);
1637         return null;
1638       }
1639     };
1640 
1641     verifyAllowed(tableRead, SUPERUSER, userTable);
1642     verifyDenied(tableRead, userColumn, userQualifier);
1643 
1644     verifyAllowed(columnRead, SUPERUSER, userTable, userColumn);
1645     verifyDenied(columnRead, userQualifier);
1646 
1647     verifyAllowed(qualifierRead, SUPERUSER, userTable, userColumn, userQualifier);
1648 
1649     verifyAllowed(multiQualifierRead, SUPERUSER, userTable, userColumn);
1650     verifyDenied(multiQualifierRead, userQualifier);
1651 
1652     verifyAllowed(globalAndTableRead, SUPERUSER);
1653     verifyDenied(globalAndTableRead, userTable, userColumn, userQualifier);
1654 
1655     verifyAllowed(noCheck, SUPERUSER, userTable, userColumn, userQualifier);
1656 
1657     // --------------------------------------
1658     // test family level multiple permissions
1659     AccessTestAction familyReadWrite = new AccessTestAction() {
1660       @Override
1661       public Void run() throws Exception {
1662         checkTablePerms(TEST_UTIL, TEST_TABLE.getTableName(), TEST_FAMILY, null,
1663           Permission.Action.READ, Permission.Action.WRITE);
1664         return null;
1665       }
1666     };
1667 
1668     verifyAllowed(familyReadWrite, SUPERUSER, USER_OWNER, USER_CREATE, USER_RW);
1669     verifyDenied(familyReadWrite, USER_NONE, USER_RO);
1670 
1671     // --------------------------------------
1672     // check for wrong table region
1673     CheckPermissionsRequest checkRequest = CheckPermissionsRequest.newBuilder()
1674       .addPermission(AccessControlProtos.Permission.newBuilder()
1675           .setType(AccessControlProtos.Permission.Type.Table)
1676           .setTablePermission(
1677               AccessControlProtos.TablePermission.newBuilder()
1678                   .setTableName(ProtobufUtil.toProtoTableName(TEST_TABLE.getTableName()))
1679                   .addAction(AccessControlProtos.Permission.Action.CREATE))
1680       ).build();
1681     Table acl = systemUserConnection.getTable(AccessControlLists.ACL_TABLE_NAME);
1682     try {
1683       BlockingRpcChannel channel = acl.coprocessorService(new byte[0]);
1684       AccessControlService.BlockingInterface protocol =
1685         AccessControlService.newBlockingStub(channel);
1686       try {
1687         // but ask for TablePermissions for TEST_TABLE
1688         protocol.checkPermissions(null, checkRequest);
1689         fail("this should have thrown CoprocessorException");
1690       } catch (ServiceException ex) {
1691         // expected
1692       }
1693     } finally {
1694       acl.close();
1695     }
1696   }
1697 
1698   @Test
1699   public void testStopRegionServer() throws Exception {
1700     AccessTestAction action = new AccessTestAction() {
1701       @Override
1702       public Object run() throws Exception {
1703         ACCESS_CONTROLLER.preStopRegionServer(ObserverContext.createAndPrepare(RSCP_ENV, null));
1704         return null;
1705       }
1706     };
1707 
1708     verifyAllowed(action, SUPERUSER, USER_ADMIN);
1709     verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO, USER_NONE);
1710   }
1711 
1712   @Test
1713   public void testRollWALWriterRequest() throws Exception {
1714     AccessTestAction action = new AccessTestAction() {
1715       @Override
1716       public Object run() throws Exception {
1717         ACCESS_CONTROLLER.preRollWALWriterRequest(ObserverContext.createAndPrepare(RSCP_ENV, null));
1718         return null;
1719       }
1720     };
1721 
1722     verifyAllowed(action, SUPERUSER, USER_ADMIN);
1723     verifyDenied(action, USER_CREATE, USER_OWNER, USER_RW, USER_RO, USER_NONE);
1724   }
1725 
1726   @Test
1727   public void testOpenRegion() throws Exception {
1728     AccessTestAction action = new AccessTestAction() {
1729       @Override
1730       public Object run() throws Exception {
1731         ACCESS_CONTROLLER.preOpen(ObserverContext.createAndPrepare(RCP_ENV, null));
1732         return null;
1733       }
1734     };
1735 
1736     verifyAllowed(action, SUPERUSER, USER_ADMIN);
1737     verifyDenied(action, USER_CREATE, USER_RW, USER_RO, USER_NONE, USER_OWNER);
1738   }
1739 
1740   @Test
1741   public void testCloseRegion() throws Exception {
1742     AccessTestAction action = new AccessTestAction() {
1743       @Override
1744       public Object run() throws Exception {
1745         ACCESS_CONTROLLER.preClose(ObserverContext.createAndPrepare(RCP_ENV, null), false);
1746         return null;
1747       }
1748     };
1749 
1750     verifyAllowed(action, SUPERUSER, USER_ADMIN);
1751     verifyDenied(action, USER_CREATE, USER_RW, USER_RO, USER_NONE, USER_OWNER);
1752   }
1753 
1754   @Test
1755   public void testSnapshot() throws Exception {
1756     Admin admin = TEST_UTIL.getHBaseAdmin();
1757     final HTableDescriptor htd = admin.getTableDescriptor(TEST_TABLE.getTableName());
1758     SnapshotDescription.Builder builder = SnapshotDescription.newBuilder();
1759     builder.setName(TEST_TABLE.getTableName().getNameAsString() + "-snapshot");
1760     builder.setTable(TEST_TABLE.getTableName().getNameAsString());
1761     final SnapshotDescription snapshot = builder.build();
1762     AccessTestAction snapshotAction = new AccessTestAction() {
1763       @Override
1764       public Object run() throws Exception {
1765         ACCESS_CONTROLLER.preSnapshot(ObserverContext.createAndPrepare(CP_ENV, null),
1766           snapshot, htd);
1767         return null;
1768       }
1769     };
1770 
1771     AccessTestAction deleteAction = new AccessTestAction() {
1772       @Override
1773       public Object run() throws Exception {
1774         ACCESS_CONTROLLER.preDeleteSnapshot(ObserverContext.createAndPrepare(CP_ENV, null),
1775           snapshot);
1776         return null;
1777       }
1778     };
1779 
1780     AccessTestAction restoreAction = new AccessTestAction() {
1781       @Override
1782       public Object run() throws Exception {
1783         ACCESS_CONTROLLER.preRestoreSnapshot(ObserverContext.createAndPrepare(CP_ENV, null),
1784           snapshot, htd);
1785         return null;
1786       }
1787     };
1788 
1789     AccessTestAction cloneAction = new AccessTestAction() {
1790       @Override
1791       public Object run() throws Exception {
1792         ACCESS_CONTROLLER.preCloneSnapshot(ObserverContext.createAndPrepare(CP_ENV, null),
1793           null, null);
1794         return null;
1795       }
1796     };
1797 
1798     verifyAllowed(snapshotAction, SUPERUSER, USER_ADMIN, USER_OWNER);
1799     verifyDenied(snapshotAction, USER_CREATE, USER_RW, USER_RO, USER_NONE);
1800 
1801     verifyAllowed(cloneAction, SUPERUSER, USER_ADMIN);
1802     verifyDenied(deleteAction, USER_CREATE, USER_RW, USER_RO, USER_NONE, USER_OWNER);
1803 
1804     verifyAllowed(restoreAction, SUPERUSER, USER_ADMIN);
1805     verifyDenied(restoreAction, USER_CREATE, USER_RW, USER_RO, USER_NONE, USER_OWNER);
1806 
1807     verifyAllowed(deleteAction, SUPERUSER, USER_ADMIN);
1808     verifyDenied(cloneAction, USER_CREATE, USER_RW, USER_RO, USER_NONE, USER_OWNER);
1809   }
1810 
1811   @Test
1812   public void testSnapshotWithOwner() throws Exception {
1813     Admin admin = TEST_UTIL.getHBaseAdmin();
1814     final HTableDescriptor htd = admin.getTableDescriptor(TEST_TABLE.getTableName());
1815     SnapshotDescription.Builder builder = SnapshotDescription.newBuilder();
1816     builder.setName(TEST_TABLE.getTableName().getNameAsString() + "-snapshot");
1817     builder.setTable(TEST_TABLE.getTableName().getNameAsString());
1818     builder.setOwner(USER_OWNER.getName());
1819     final SnapshotDescription snapshot = builder.build();
1820     AccessTestAction snapshotAction = new AccessTestAction() {
1821       @Override
1822       public Object run() throws Exception {
1823         ACCESS_CONTROLLER.preSnapshot(ObserverContext.createAndPrepare(CP_ENV, null),
1824           snapshot, htd);
1825         return null;
1826       }
1827     };
1828     verifyAllowed(snapshotAction, SUPERUSER, USER_ADMIN, USER_OWNER);
1829     verifyDenied(snapshotAction, USER_CREATE, USER_RW, USER_RO, USER_NONE);
1830 
1831     AccessTestAction deleteAction = new AccessTestAction() {
1832       @Override
1833       public Object run() throws Exception {
1834         ACCESS_CONTROLLER.preDeleteSnapshot(ObserverContext.createAndPrepare(CP_ENV, null),
1835           snapshot);
1836         return null;
1837       }
1838     };
1839     verifyAllowed(deleteAction, SUPERUSER, USER_ADMIN, USER_OWNER);
1840     verifyDenied(deleteAction, USER_CREATE, USER_RW, USER_RO, USER_NONE);
1841 
1842     AccessTestAction restoreAction = new AccessTestAction() {
1843       @Override
1844       public Object run() throws Exception {
1845         ACCESS_CONTROLLER.preRestoreSnapshot(ObserverContext.createAndPrepare(CP_ENV, null),
1846           snapshot, htd);
1847         return null;
1848       }
1849     };
1850     verifyAllowed(restoreAction, SUPERUSER, USER_ADMIN, USER_OWNER);
1851     verifyDenied(restoreAction, USER_CREATE, USER_RW, USER_RO, USER_NONE);
1852 
1853     AccessTestAction cloneAction = new AccessTestAction() {
1854       @Override
1855       public Object run() throws Exception {
1856         ACCESS_CONTROLLER.preCloneSnapshot(ObserverContext.createAndPrepare(CP_ENV, null),
1857           null, null);
1858         return null;
1859       }
1860     };
1861     // Clone by snapshot owner is not allowed , because clone operation creates a new table,
1862     // which needs global admin permission.
1863     verifyAllowed(cloneAction, SUPERUSER, USER_ADMIN);
1864     verifyDenied(cloneAction, USER_CREATE, USER_RW, USER_RO, USER_NONE, USER_OWNER);
1865   }
1866 
1867   @Test
1868   public void testGlobalAuthorizationForNewRegisteredRS() throws Exception {
1869     LOG.debug("Test for global authorization for a new registered RegionServer.");
1870     MiniHBaseCluster hbaseCluster = TEST_UTIL.getHBaseCluster();
1871 
1872     // Since each RegionServer running on different user, add global
1873     // permissions for the new user.
1874     String currentUser = User.getCurrent().getShortName();
1875     String activeUserForNewRs = currentUser + ".hfs." +
1876       hbaseCluster.getLiveRegionServerThreads().size();
1877     grantGlobal(TEST_UTIL, activeUserForNewRs,
1878       Permission.Action.ADMIN, Permission.Action.CREATE, Permission.Action.READ,
1879         Permission.Action.WRITE);
1880 
1881     final Admin admin = TEST_UTIL.getHBaseAdmin();
1882     HTableDescriptor htd = new HTableDescriptor(TEST_TABLE2);
1883     htd.addFamily(new HColumnDescriptor(TEST_FAMILY));
1884     createTable(TEST_UTIL, htd);
1885 
1886     // Starting a new RegionServer.
1887     JVMClusterUtil.RegionServerThread newRsThread = hbaseCluster
1888         .startRegionServer();
1889     final HRegionServer newRs = newRsThread.getRegionServer();
1890 
1891     // Move region to the new RegionServer.
1892     List<HRegionLocation> regions;
1893     try (RegionLocator locator = systemUserConnection.getRegionLocator(TEST_TABLE2)) {
1894       regions = locator.getAllRegionLocations();
1895     }
1896     HRegionLocation location = regions.get(0);
1897     final HRegionInfo hri = location.getRegionInfo();
1898     final ServerName server = location.getServerName();
1899     try (HTable table = (HTable) systemUserConnection.getTable(TEST_TABLE2)) {
1900       AccessTestAction moveAction = new AccessTestAction() {
1901         @Override
1902         public Object run() throws Exception {
1903           admin.move(hri.getEncodedNameAsBytes(),
1904             Bytes.toBytes(newRs.getServerName().getServerName()));
1905           return null;
1906         }
1907       };
1908       SUPERUSER.runAs(moveAction);
1909 
1910       final int RETRIES_LIMIT = 10;
1911       int retries = 0;
1912       while (newRs.getOnlineRegions(TEST_TABLE2).size() < 1 && retries < RETRIES_LIMIT) {
1913         LOG.debug("Waiting for region to be opened. Already retried " + retries
1914             + " times.");
1915         try {
1916           Thread.sleep(1000);
1917         } catch (InterruptedException e) {
1918         }
1919         retries++;
1920         if (retries == RETRIES_LIMIT - 1) {
1921           fail("Retry exhaust for waiting region to be opened.");
1922         }
1923       }
1924       // Verify write permission for user "admin2" who has the global
1925       // permissions.
1926       AccessTestAction putAction = new AccessTestAction() {
1927         @Override
1928         public Object run() throws Exception {
1929           Put put = new Put(Bytes.toBytes("test"));
1930           put.add(TEST_FAMILY, Bytes.toBytes("qual"), Bytes.toBytes("value"));
1931           table.put(put);
1932           return null;
1933         }
1934       };
1935       USER_ADMIN.runAs(putAction);
1936     }
1937   }
1938 
1939   @Test
1940   public void testTableDescriptorsEnumeration() throws Exception {
1941     User TABLE_ADMIN = User.createUserForTesting(conf, "UserA", new String[0]);
1942 
1943     // Grant TABLE ADMIN privs
1944     grantOnTable(TEST_UTIL, TABLE_ADMIN.getShortName(),
1945       TEST_TABLE.getTableName(), null, null,
1946       Permission.Action.ADMIN);
1947 
1948     AccessTestAction listTablesAction = new AccessTestAction() {
1949       @Override
1950       public Object run() throws Exception {
1951         try(Connection conn = ConnectionFactory.createConnection(TEST_UTIL.getConfiguration());
1952              Admin admin = conn.getAdmin()) {
1953           return Arrays.asList(admin.listTables());
1954         }
1955       }
1956     };
1957 
1958     AccessTestAction getTableDescAction = new AccessTestAction() {
1959       @Override
1960       public Object run() throws Exception {
1961         try(Connection conn = ConnectionFactory.createConnection(TEST_UTIL.getConfiguration());
1962             Admin admin = conn.getAdmin();) {
1963           return admin.getTableDescriptor(TEST_TABLE.getTableName());
1964         }
1965       }
1966     };
1967 
1968     verifyAllowed(listTablesAction, SUPERUSER, USER_ADMIN, USER_CREATE, TABLE_ADMIN);
1969     verifyIfEmptyList(listTablesAction, USER_RW, USER_RO, USER_NONE);
1970 
1971     verifyAllowed(getTableDescAction, SUPERUSER, USER_ADMIN, USER_CREATE, TABLE_ADMIN);
1972     verifyDenied(getTableDescAction, USER_RW, USER_RO, USER_NONE);
1973   }
1974 
1975   @Test
1976   public void testTableNameEnumeration() throws Exception {
1977     AccessTestAction listTablesAction = new AccessTestAction() {
1978       @Override
1979       public Object run() throws Exception {
1980         Connection unmanagedConnection =
1981             ConnectionFactory.createConnection(TEST_UTIL.getConfiguration());
1982         Admin admin = unmanagedConnection.getAdmin();
1983         try {
1984           return Arrays.asList(admin.listTableNames());
1985         } finally {
1986           admin.close();
1987           unmanagedConnection.close();
1988         }
1989       }
1990     };
1991 
1992     verifyAllowed(listTablesAction, SUPERUSER, USER_ADMIN, USER_CREATE, USER_RW, USER_RO);
1993     verifyIfEmptyList(listTablesAction, USER_NONE);
1994   }
1995 
1996   @Test
1997   public void testTableDeletion() throws Exception {
1998     User TABLE_ADMIN = User.createUserForTesting(conf, "TestUser", new String[0]);
1999 
2000     // Grant TABLE ADMIN privs
2001     grantOnTable(TEST_UTIL, TABLE_ADMIN.getShortName(),
2002       TEST_TABLE.getTableName(), null, null,
2003       Permission.Action.ADMIN);
2004 
2005     AccessTestAction deleteTableAction = new AccessTestAction() {
2006       @Override
2007       public Object run() throws Exception {
2008         Connection unmanagedConnection = ConnectionFactory.createConnection(TEST_UTIL.getConfiguration());
2009         Admin admin = unmanagedConnection.getAdmin();
2010         try {
2011           deleteTable(TEST_UTIL, admin, TEST_TABLE.getTableName());
2012         } finally {
2013           admin.close();
2014           unmanagedConnection.close();
2015         }
2016         return null;
2017       }
2018     };
2019 
2020     verifyDenied(deleteTableAction, USER_RW, USER_RO, USER_NONE);
2021     verifyAllowed(deleteTableAction, TABLE_ADMIN);
2022   }
2023 
2024   @Test
2025   public void testNamespaceUserGrant() throws Exception {
2026     AccessTestAction getAction = new AccessTestAction() {
2027       @Override
2028       public Object run() throws Exception {
2029         try(Connection conn = ConnectionFactory.createConnection(conf);
2030             Table t = conn.getTable(TEST_TABLE.getTableName());) {
2031           return t.get(new Get(TEST_ROW));
2032         }
2033       }
2034     };
2035 
2036     String namespace = TEST_TABLE.getTableName().getNamespaceAsString();
2037 
2038     // Grant namespace READ to USER_NONE, this should supersede any table permissions
2039     grantOnNamespace(TEST_UTIL, USER_NONE.getShortName(), namespace, Permission.Action.READ);
2040     // Now USER_NONE should be able to read
2041     verifyAllowed(getAction, USER_NONE);
2042 
2043     // Revoke namespace READ to USER_NONE
2044     revokeFromNamespace(TEST_UTIL, USER_NONE.getShortName(), namespace, Permission.Action.READ);
2045     verifyDenied(getAction, USER_NONE);
2046   }
2047 
2048   @Test
2049   public void testAccessControlClientGrantRevoke() throws Exception {
2050     // Create user for testing, who has no READ privileges by default.
2051     User testGrantRevoke = User.createUserForTesting(conf, "testGrantRevoke", new String[0]);
2052     AccessTestAction getAction = new AccessTestAction() {
2053       @Override
2054       public Object run() throws Exception {
2055         try(Connection conn = ConnectionFactory.createConnection(conf);
2056             Table t = conn.getTable(TEST_TABLE.getTableName())) {
2057           return t.get(new Get(TEST_ROW));
2058         }
2059       }
2060     };
2061 
2062     verifyDenied(getAction, testGrantRevoke);
2063 
2064     // Grant table READ permissions to testGrantRevoke.
2065     try {
2066       grantOnTableUsingAccessControlClient(TEST_UTIL, systemUserConnection, testGrantRevoke.getShortName(),
2067           TEST_TABLE.getTableName(), null, null, Permission.Action.READ);
2068     } catch (Throwable e) {
2069       LOG.error("error during call of AccessControlClient.grant. ", e);
2070     }
2071 
2072     // Now testGrantRevoke should be able to read also
2073     verifyAllowed(getAction, testGrantRevoke);
2074 
2075     // Revoke table READ permission to testGrantRevoke.
2076     try {
2077       revokeFromTableUsingAccessControlClient(TEST_UTIL, systemUserConnection, testGrantRevoke.getShortName(),
2078           TEST_TABLE.getTableName(), null, null, Permission.Action.READ);
2079     } catch (Throwable e) {
2080       LOG.error("error during call of AccessControlClient.revoke ", e);
2081     }
2082 
2083     // Now testGrantRevoke shouldn't be able read
2084     verifyDenied(getAction, testGrantRevoke);
2085   }
2086 
2087   @Test
2088   public void testAccessControlClientGlobalGrantRevoke() throws Exception {
2089     // Create user for testing, who has no READ privileges by default.
2090     User testGlobalGrantRevoke = User.createUserForTesting(conf,
2091       "testGlobalGrantRevoke", new String[0]);
2092     AccessTestAction getAction = new AccessTestAction() {
2093       @Override
2094       public Object run() throws Exception {
2095         try(Connection conn = ConnectionFactory.createConnection(conf);
2096             Table t = conn.getTable(TEST_TABLE.getTableName())) {
2097           return t.get(new Get(TEST_ROW));
2098         }
2099       }
2100     };
2101 
2102     verifyDenied(getAction, testGlobalGrantRevoke);
2103 
2104     // Grant table READ permissions to testGlobalGrantRevoke.
2105     try {
2106       grantGlobalUsingAccessControlClient(TEST_UTIL, systemUserConnection,
2107           testGlobalGrantRevoke.getShortName(), Permission.Action.READ);
2108     } catch (Throwable e) {
2109       LOG.error("error during call of AccessControlClient.grant. ", e);
2110     }
2111 
2112     // Now testGlobalGrantRevoke should be able to read also
2113     verifyAllowed(getAction, testGlobalGrantRevoke);
2114 
2115     // Revoke table READ permission to testGlobalGrantRevoke.
2116     try {
2117       revokeGlobalUsingAccessControlClient(TEST_UTIL, systemUserConnection,
2118           testGlobalGrantRevoke.getShortName(), Permission.Action.READ);
2119     } catch (Throwable e) {
2120       LOG.error("error during call of AccessControlClient.revoke ", e);
2121     }
2122 
2123     // Now testGlobalGrantRevoke shouldn't be able read
2124     verifyDenied(getAction, testGlobalGrantRevoke);
2125   }
2126 
2127   @Test
2128   public void testAccessControlClientGrantRevokeOnNamespace() throws Exception {
2129     // Create user for testing, who has no READ privileges by default.
2130     User testNS = User.createUserForTesting(conf, "testNS", new String[0]);
2131     AccessTestAction getAction = new AccessTestAction() {
2132       @Override
2133       public Object run() throws Exception {
2134         try(Connection conn = ConnectionFactory.createConnection(conf);
2135             Table t = conn.getTable(TEST_TABLE.getTableName())) {
2136           return t.get(new Get(TEST_ROW));
2137         }
2138       }
2139     };
2140 
2141     verifyDenied(getAction, testNS);
2142 
2143     // Grant namespace READ to testNS, this should supersede any table permissions
2144     try {
2145       grantOnNamespaceUsingAccessControlClient(TEST_UTIL, systemUserConnection, testNS.getShortName(),
2146           TEST_TABLE.getTableName().getNamespaceAsString(), Permission.Action.READ);
2147     } catch (Throwable e) {
2148       LOG.error("error during call of AccessControlClient.grant. ", e);
2149     }
2150 
2151     // Now testNS should be able to read also
2152     verifyAllowed(getAction, testNS);
2153 
2154     // Revoke namespace READ to testNS, this should supersede any table permissions
2155     try {
2156       revokeFromNamespaceUsingAccessControlClient(TEST_UTIL, systemUserConnection, testNS.getShortName(),
2157           TEST_TABLE.getTableName().getNamespaceAsString(), Permission.Action.READ);
2158     } catch (Throwable e) {
2159       LOG.error("error during call of AccessControlClient.revoke ", e);
2160     }
2161 
2162     // Now testNS shouldn't be able read
2163     verifyDenied(getAction, testNS);
2164   }
2165 
2166 
2167   public static class PingCoprocessor extends PingService implements Coprocessor,
2168       CoprocessorService {
2169 
2170     @Override
2171     public void start(CoprocessorEnvironment env) throws IOException { }
2172 
2173     @Override
2174     public void stop(CoprocessorEnvironment env) throws IOException { }
2175 
2176     @Override
2177     public Service getService() {
2178       return this;
2179     }
2180 
2181     @Override
2182     public void ping(RpcController controller, PingRequest request,
2183         RpcCallback<PingResponse> callback) {
2184       callback.run(PingResponse.newBuilder().setPong("Pong!").build());
2185     }
2186 
2187     @Override
2188     public void count(RpcController controller, CountRequest request,
2189         RpcCallback<CountResponse> callback) {
2190       callback.run(CountResponse.newBuilder().build());
2191     }
2192 
2193     @Override
2194     public void increment(RpcController controller, IncrementCountRequest requet,
2195         RpcCallback<IncrementCountResponse> callback) {
2196       callback.run(IncrementCountResponse.newBuilder().build());
2197     }
2198 
2199     @Override
2200     public void hello(RpcController controller, HelloRequest request,
2201         RpcCallback<HelloResponse> callback) {
2202       callback.run(HelloResponse.newBuilder().setResponse("Hello!").build());
2203     }
2204 
2205     @Override
2206     public void noop(RpcController controller, NoopRequest request,
2207         RpcCallback<NoopResponse> callback) {
2208       callback.run(NoopResponse.newBuilder().build());
2209     }
2210   }
2211 
2212   @Test
2213   public void testCoprocessorExec() throws Exception {
2214     // Set up our ping endpoint service on all regions of our test table
2215     for (JVMClusterUtil.RegionServerThread thread:
2216         TEST_UTIL.getMiniHBaseCluster().getRegionServerThreads()) {
2217       HRegionServer rs = thread.getRegionServer();
2218       for (Region region: rs.getOnlineRegions(TEST_TABLE.getTableName())) {
2219         region.getCoprocessorHost().load(PingCoprocessor.class,
2220           Coprocessor.PRIORITY_USER, conf);
2221       }
2222     }
2223 
2224     // Create users for testing, and grant EXEC privileges on our test table
2225     // only to user A
2226     User userA = User.createUserForTesting(conf, "UserA", new String[0]);
2227     User userB = User.createUserForTesting(conf, "UserB", new String[0]);
2228 
2229     grantOnTable(TEST_UTIL, userA.getShortName(),
2230       TEST_TABLE.getTableName(), null, null,
2231       Permission.Action.EXEC);
2232 
2233     // Create an action for invoking our test endpoint
2234     AccessTestAction execEndpointAction = new AccessTestAction() {
2235       @Override
2236       public Object run() throws Exception {
2237         try(Connection conn = ConnectionFactory.createConnection(conf);
2238             Table t = conn.getTable(TEST_TABLE.getTableName());) {
2239           BlockingRpcChannel service = t.coprocessorService(HConstants.EMPTY_BYTE_ARRAY);
2240           PingCoprocessor.newBlockingStub(service).noop(null, NoopRequest.newBuilder().build());
2241         }
2242         return null;
2243       }
2244     };
2245 
2246     String namespace = TEST_TABLE.getTableName().getNamespaceAsString();
2247     // Now grant EXEC to the entire namespace to user B
2248     grantOnNamespace(TEST_UTIL, userB.getShortName(), namespace, Permission.Action.EXEC);
2249     // User B should now be allowed also
2250     verifyAllowed(execEndpointAction, userA, userB);
2251 
2252     revokeFromNamespace(TEST_UTIL, userB.getShortName(), namespace, Permission.Action.EXEC);
2253     // Verify that EXEC permission is checked correctly
2254     verifyDenied(execEndpointAction, userB);
2255     verifyAllowed(execEndpointAction, userA);
2256   }
2257 
2258   @Test
2259   public void testReservedCellTags() throws Exception {
2260     AccessTestAction putWithReservedTag = new AccessTestAction() {
2261       @Override
2262       public Object run() throws Exception {
2263         Table t = new HTable(conf, TEST_TABLE.getTableName());
2264         try {
2265           KeyValue kv = new KeyValue(TEST_ROW, TEST_FAMILY, TEST_QUALIFIER,
2266             HConstants.LATEST_TIMESTAMP, HConstants.EMPTY_BYTE_ARRAY,
2267             new Tag[] { new Tag(AccessControlLists.ACL_TAG_TYPE,
2268               ProtobufUtil.toUsersAndPermissions(USER_OWNER.getShortName(),
2269                 new Permission(Permission.Action.READ)).toByteArray()) });
2270           t.put(new Put(TEST_ROW).add(kv));
2271         } finally {
2272           t.close();
2273         }
2274         return null;
2275       }
2276     };
2277 
2278     // Current user is superuser
2279     verifyAllowed(putWithReservedTag, User.getCurrent());
2280     // No other user should be allowed
2281     verifyDenied(putWithReservedTag, USER_OWNER, USER_ADMIN, USER_CREATE, USER_RW, USER_RO);
2282   }
2283 
2284    @Test
2285    public void testGetNamespacePermission() throws Exception {
2286      String namespace = "testGetNamespacePermission";
2287      NamespaceDescriptor desc = NamespaceDescriptor.create(namespace).build();
2288      createNamespace(TEST_UTIL, desc);
2289      grantOnNamespace(TEST_UTIL, USER_NONE.getShortName(), namespace, Permission.Action.READ);
2290      try {
2291        List<UserPermission> namespacePermissions = AccessControlClient.getUserPermissions(
2292            systemUserConnection, AccessControlLists.toNamespaceEntry(namespace));
2293        assertTrue(namespacePermissions != null);
2294        assertTrue(namespacePermissions.size() == 1);
2295      } catch (Throwable thw) {
2296        throw new HBaseException(thw);
2297      }
2298      deleteNamespace(TEST_UTIL, namespace);
2299    }
2300 
2301   @Test
2302   public void testTruncatePerms() throws Throwable {
2303     List<UserPermission> existingPerms =
2304         AccessControlClient.getUserPermissions(systemUserConnection,
2305             TEST_TABLE.getTableName().getNameAsString());
2306     assertTrue(existingPerms != null);
2307     assertTrue(existingPerms.size() > 1);
2308     try (Admin admin = systemUserConnection.getAdmin()) {
2309       admin.disableTable(TEST_TABLE.getTableName());
2310       admin.truncateTable(TEST_TABLE.getTableName(), true);
2311     }
2312     List<UserPermission> perms = AccessControlClient.getUserPermissions(systemUserConnection,
2313         TEST_TABLE.getTableName().getNameAsString());
2314     assertTrue(perms != null);
2315     assertEquals(existingPerms.size(), perms.size());
2316   }
2317 
2318   private PrivilegedAction<List<UserPermission>> getPrivilegedAction(final String regex) {
2319     return new PrivilegedAction<List<UserPermission>>() {
2320       @Override
2321       public List<UserPermission> run() {
2322         try(Connection conn = ConnectionFactory.createConnection(conf);) {
2323           return AccessControlClient.getUserPermissions(conn, regex);
2324         } catch (Throwable e) {
2325           LOG.error("error during call of AccessControlClient.getUserPermissions.", e);
2326           return null;
2327         }
2328       }
2329     };
2330   }
2331 
2332   @Test
2333   public void testAccessControlClientUserPerms() throws Exception {
2334     // adding default prefix explicitly as it is not included in the table name.
2335     assertEquals(NamespaceDescriptor.DEFAULT_NAMESPACE_NAME_STR,
2336                  TEST_TABLE.getTableName().getNamespaceAsString());
2337     final String regex = NamespaceDescriptor.DEFAULT_NAMESPACE_NAME_STR +
2338       TableName.NAMESPACE_DELIM + TEST_TABLE.getTableName().getNameAsString();
2339     User testUserPerms = User.createUserForTesting(conf, "testUserPerms", new String[0]);
2340     assertEquals(0, testUserPerms.runAs(getPrivilegedAction(regex)).size());
2341     // Grant TABLE ADMIN privs to testUserPerms
2342     grantOnTable(TEST_UTIL, testUserPerms.getShortName(), TEST_TABLE.getTableName(), null,
2343       null, Action.ADMIN);
2344     List<UserPermission> perms = testUserPerms.runAs(getPrivilegedAction(regex));
2345     assertNotNull(perms);
2346     // USER_ADMIN, USER_CREATE, USER_RW, USER_RO, testUserPerms, USER_ADMIN_CF has row each.
2347     assertEquals(6, perms.size());
2348   }
2349 
2350   @Test
2351   public void testAccessControllerUserPermsRegexHandling() throws Exception {
2352     User testRegexHandler = User.createUserForTesting(conf, "testRegexHandling", new String[0]);
2353 
2354     final String REGEX_ALL_TABLES = ".*";
2355     final String tableName = "testRegex";
2356     final TableName table1 = TableName.valueOf(tableName);
2357     final byte[] family = Bytes.toBytes("f1");
2358 
2359     // create table in default ns
2360     Admin admin = TEST_UTIL.getHBaseAdmin();
2361     HTableDescriptor htd = new HTableDescriptor(table1);
2362     htd.addFamily(new HColumnDescriptor(family));
2363     createTable(TEST_UTIL, htd);
2364 
2365     // creating the ns and table in it
2366     String ns = "testNamespace";
2367     NamespaceDescriptor desc = NamespaceDescriptor.create(ns).build();
2368     final TableName table2 = TableName.valueOf(ns, tableName);
2369     createNamespace(TEST_UTIL, desc);
2370     htd = new HTableDescriptor(table2);
2371     htd.addFamily(new HColumnDescriptor(family));
2372     createTable(TEST_UTIL, htd);
2373 
2374     // Verify that we can read sys-tables
2375     String aclTableName = AccessControlLists.ACL_TABLE_NAME.getNameAsString();
2376     assertEquals(1, SUPERUSER.runAs(getPrivilegedAction(aclTableName)).size());
2377     assertEquals(0, testRegexHandler.runAs(getPrivilegedAction(aclTableName)).size());
2378 
2379     // Grant TABLE ADMIN privs to testUserPerms
2380     assertEquals(0, testRegexHandler.runAs(getPrivilegedAction(REGEX_ALL_TABLES)).size());
2381     grantOnTable(TEST_UTIL, testRegexHandler.getShortName(), table1, null, null, Action.ADMIN);
2382     assertEquals(2, testRegexHandler.runAs(getPrivilegedAction(REGEX_ALL_TABLES)).size());
2383     grantOnTable(TEST_UTIL, testRegexHandler.getShortName(), table2, null, null, Action.ADMIN);
2384     assertEquals(4, testRegexHandler.runAs(getPrivilegedAction(REGEX_ALL_TABLES)).size());
2385 
2386     // USER_ADMIN, testUserPerms must have a row each.
2387     assertEquals(2, testRegexHandler.runAs(getPrivilegedAction(tableName)).size());
2388     assertEquals(2, testRegexHandler.runAs(getPrivilegedAction(
2389           NamespaceDescriptor.DEFAULT_NAMESPACE_NAME_STR + TableName.NAMESPACE_DELIM + tableName)
2390         ).size());
2391     assertEquals(2, testRegexHandler.runAs(getPrivilegedAction(
2392         ns + TableName.NAMESPACE_DELIM + tableName)).size());
2393     assertEquals(0, testRegexHandler.runAs(getPrivilegedAction("notMatchingAny")).size());
2394 
2395     deleteTable(TEST_UTIL, table1);
2396     deleteTable(TEST_UTIL, table2);
2397     deleteNamespace(TEST_UTIL, ns);
2398   }
2399 
2400   private void verifyAnyCreate(AccessTestAction action) throws Exception {
2401     verifyAllowed(action, SUPERUSER, USER_ADMIN, USER_OWNER, USER_CREATE, USER_ADMIN_CF);
2402     verifyDenied(action, USER_NONE, USER_RO, USER_RW);
2403   }
2404 
2405   @Test
2406   public void testPrepareAndCleanBulkLoad() throws Exception {
2407     AccessTestAction prepareBulkLoadAction = new AccessTestAction() {
2408       @Override
2409       public Object run() throws Exception {
2410         ACCESS_CONTROLLER.prePrepareBulkLoad(ObserverContext.createAndPrepare(RCP_ENV, null), null);
2411         return null;
2412       }
2413     };
2414     AccessTestAction cleanupBulkLoadAction = new AccessTestAction() {
2415       @Override
2416       public Object run() throws Exception {
2417         ACCESS_CONTROLLER.preCleanupBulkLoad(ObserverContext.createAndPrepare(RCP_ENV, null), null);
2418         return null;
2419       }
2420     };
2421     verifyAnyCreate(prepareBulkLoadAction);
2422     verifyAnyCreate(cleanupBulkLoadAction);
2423   }
2424 
2425   @Test
2426   public void testReplicateLogEntries() throws Exception {
2427     AccessTestAction replicateLogEntriesAction = new AccessTestAction() {
2428       @Override
2429       public Object run() throws Exception {
2430         ACCESS_CONTROLLER.preReplicateLogEntries(ObserverContext.createAndPrepare(RSCP_ENV, null),
2431           null, null);
2432         ACCESS_CONTROLLER.postReplicateLogEntries(ObserverContext.createAndPrepare(RSCP_ENV, null),
2433           null, null);
2434         return null;
2435       }
2436     };
2437 
2438     verifyAllowed(replicateLogEntriesAction, SUPERUSER, USER_ADMIN);
2439     verifyDenied(replicateLogEntriesAction, USER_CREATE, USER_RW, USER_RO, USER_NONE, USER_OWNER);
2440   }
2441   
2442   @Test
2443   public void testSetQuota() throws Exception {
2444     AccessTestAction setUserQuotaAction = new AccessTestAction() {
2445       @Override
2446       public Object run() throws Exception {
2447         ACCESS_CONTROLLER.preSetUserQuota(ObserverContext.createAndPrepare(CP_ENV, null),
2448           null, null);
2449         return null;
2450       }
2451     };
2452 
2453     AccessTestAction setUserTableQuotaAction = new AccessTestAction() {
2454       @Override
2455       public Object run() throws Exception {
2456         ACCESS_CONTROLLER.preSetUserQuota(ObserverContext.createAndPrepare(CP_ENV, null),
2457           null, TEST_TABLE.getTableName(), null);
2458         return null;
2459       }
2460     };
2461 
2462     AccessTestAction setUserNamespaceQuotaAction = new AccessTestAction() {
2463       @Override
2464       public Object run() throws Exception {
2465         ACCESS_CONTROLLER.preSetUserQuota(ObserverContext.createAndPrepare(CP_ENV, null),
2466           null, (String)null, null);
2467         return null;
2468       }
2469     };
2470 
2471     AccessTestAction setTableQuotaAction = new AccessTestAction() {
2472       @Override
2473       public Object run() throws Exception {
2474         ACCESS_CONTROLLER.preSetTableQuota(ObserverContext.createAndPrepare(CP_ENV, null),
2475           TEST_TABLE.getTableName(), null);
2476         return null;
2477       }
2478     };
2479 
2480     AccessTestAction setNamespaceQuotaAction = new AccessTestAction() {
2481       @Override
2482       public Object run() throws Exception {
2483         ACCESS_CONTROLLER.preSetNamespaceQuota(ObserverContext.createAndPrepare(CP_ENV, null),
2484           null, null);
2485         return null;
2486       }
2487     };
2488 
2489     verifyAllowed(setUserQuotaAction, SUPERUSER, USER_ADMIN);
2490     verifyDenied(setUserQuotaAction, USER_CREATE, USER_RW, USER_RO, USER_NONE, USER_OWNER);
2491 
2492     verifyAllowed(setUserTableQuotaAction, SUPERUSER, USER_ADMIN, USER_OWNER);
2493     verifyDenied(setUserTableQuotaAction, USER_CREATE, USER_RW, USER_RO, USER_NONE);
2494 
2495     verifyAllowed(setUserNamespaceQuotaAction, SUPERUSER, USER_ADMIN);
2496     verifyDenied(setUserNamespaceQuotaAction, USER_CREATE, USER_RW, USER_RO, USER_NONE, USER_OWNER);
2497 
2498     verifyAllowed(setTableQuotaAction, SUPERUSER, USER_ADMIN, USER_OWNER);
2499     verifyDenied(setTableQuotaAction, USER_CREATE, USER_RW, USER_RO, USER_NONE);
2500 
2501     verifyAllowed(setNamespaceQuotaAction, SUPERUSER, USER_ADMIN);
2502     verifyDenied(setNamespaceQuotaAction, USER_CREATE, USER_RW, USER_RO, USER_NONE, USER_OWNER);
2503   }
2504 }