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