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