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 java.io.ByteArrayInputStream;
22  import java.io.DataInput;
23  import java.io.DataInputStream;
24  import java.io.IOException;
25  import java.util.ArrayList;
26  import java.util.Arrays;
27  import java.util.Iterator;
28  import java.util.List;
29  import java.util.Map;
30  import java.util.Set;
31  import java.util.TreeMap;
32  import java.util.TreeSet;
33  
34  import com.google.common.annotations.VisibleForTesting;
35  import org.apache.commons.logging.Log;
36  import org.apache.commons.logging.LogFactory;
37  import org.apache.hadoop.conf.Configuration;
38  import org.apache.hadoop.hbase.AuthUtil;
39  import org.apache.hadoop.hbase.Cell;
40  import org.apache.hadoop.hbase.CellUtil;
41  import org.apache.hadoop.hbase.HColumnDescriptor;
42  import org.apache.hadoop.hbase.HConstants;
43  import org.apache.hadoop.hbase.HTableDescriptor;
44  import org.apache.hadoop.hbase.NamespaceDescriptor;
45  import org.apache.hadoop.hbase.TableName;
46  import org.apache.hadoop.hbase.Tag;
47  import org.apache.hadoop.hbase.TagType;
48  import org.apache.hadoop.hbase.classification.InterfaceAudience;
49  import org.apache.hadoop.hbase.client.Connection;
50  import org.apache.hadoop.hbase.client.ConnectionFactory;
51  import org.apache.hadoop.hbase.client.Delete;
52  import org.apache.hadoop.hbase.client.Get;
53  import org.apache.hadoop.hbase.client.Put;
54  import org.apache.hadoop.hbase.client.Result;
55  import org.apache.hadoop.hbase.client.ResultScanner;
56  import org.apache.hadoop.hbase.client.Scan;
57  import org.apache.hadoop.hbase.client.Table;
58  import org.apache.hadoop.hbase.exceptions.DeserializationException;
59  import org.apache.hadoop.hbase.filter.CompareFilter.CompareOp;
60  import org.apache.hadoop.hbase.filter.QualifierFilter;
61  import org.apache.hadoop.hbase.filter.RegexStringComparator;
62  import org.apache.hadoop.hbase.master.MasterServices;
63  import org.apache.hadoop.hbase.protobuf.ProtobufUtil;
64  import org.apache.hadoop.hbase.protobuf.generated.AccessControlProtos;
65  import org.apache.hadoop.hbase.regionserver.BloomType;
66  import org.apache.hadoop.hbase.regionserver.InternalScanner;
67  import org.apache.hadoop.hbase.regionserver.Region;
68  import org.apache.hadoop.hbase.security.User;
69  import org.apache.hadoop.hbase.util.Bytes;
70  import org.apache.hadoop.hbase.util.Pair;
71  import org.apache.hadoop.io.Text;
72  
73  import com.google.common.collect.ArrayListMultimap;
74  import com.google.common.collect.ListMultimap;
75  import com.google.common.collect.Lists;
76  
77  /**
78   * Maintains lists of permission grants to users and groups to allow for
79   * authorization checks by {@link AccessController}.
80   *
81   * <p>
82   * Access control lists are stored in an "internal" metadata table named
83   * {@code _acl_}. Each table's permission grants are stored as a separate row,
84   * keyed by the table name. KeyValues for permissions assignments are stored
85   * in one of the formats:
86   * <pre>
87   * Key                      Desc
88   * --------                 --------
89   * user                     table level permissions for a user [R=read, W=write]
90   * group                    table level permissions for a group
91   * user,family              column family level permissions for a user
92   * group,family             column family level permissions for a group
93   * user,family,qualifier    column qualifier level permissions for a user
94   * group,family,qualifier   column qualifier level permissions for a group
95   * </pre>
96   * <p>
97   * All values are encoded as byte arrays containing the codes from the
98   * org.apache.hadoop.hbase.security.access.TablePermission.Action enum.
99   * </p>
100  */
101 @InterfaceAudience.Private
102 public class AccessControlLists {
103   /** Internal storage table for access control lists */
104   public static final TableName ACL_TABLE_NAME =
105       TableName.valueOf(NamespaceDescriptor.SYSTEM_NAMESPACE_NAME_STR, "acl");
106   public static final byte[] ACL_GLOBAL_NAME = ACL_TABLE_NAME.getName();
107   /** Column family used to store ACL grants */
108   public static final String ACL_LIST_FAMILY_STR = "l";
109   public static final byte[] ACL_LIST_FAMILY = Bytes.toBytes(ACL_LIST_FAMILY_STR);
110   /** KV tag to store per cell access control lists */
111   public static final byte ACL_TAG_TYPE = TagType.ACL_TAG_TYPE;
112 
113   public static final char NAMESPACE_PREFIX = '@';
114 
115   /**
116    * Delimiter to separate user, column family, and qualifier in
117    * _acl_ table info: column keys */
118   public static final char ACL_KEY_DELIMITER = ',';
119 
120   private static final Log LOG = LogFactory.getLog(AccessControlLists.class);
121 
122   /**
123    * Create the ACL table
124    * @param master
125    * @throws IOException
126    */
127   static void createACLTable(MasterServices master) throws IOException {
128     /** Table descriptor for ACL table */
129     final HTableDescriptor ACL_TABLEDESC = new HTableDescriptor(ACL_TABLE_NAME)
130       .addFamily(new HColumnDescriptor(ACL_LIST_FAMILY)
131         .setMaxVersions(1)
132         .setInMemory(true)
133         .setBlockCacheEnabled(true)
134         .setBlocksize(8 * 1024)
135         .setBloomFilterType(BloomType.NONE)
136         .setScope(HConstants.REPLICATION_SCOPE_LOCAL)
137         // Set cache data blocks in L1 if more than one cache tier deployed; e.g. this will
138         // be the case if we are using CombinedBlockCache (Bucket Cache).
139         .setCacheDataInL1(true));
140     master.createSystemTable(ACL_TABLEDESC);
141   }
142 
143   static void addUserPermission(Configuration conf, UserPermission userPerm, Table t,
144       boolean mergeExistingPermissions) throws IOException {
145     Permission.Action[] actions = userPerm.getActions();
146     byte[] rowKey = userPermissionRowKey(userPerm);
147     Put p = new Put(rowKey);
148     byte[] key = userPermissionKey(userPerm);
149 
150     if ((actions == null) || (actions.length == 0)) {
151       String msg = "No actions associated with user '" + Bytes.toString(userPerm.getUser()) + "'";
152       LOG.warn(msg);
153       throw new IOException(msg);
154     }
155 
156     Set<Permission.Action> actionSet = new TreeSet<Permission.Action>();
157     if (mergeExistingPermissions) {
158       List<UserPermission> perms = getUserPermissions(conf, rowKey);
159       UserPermission currentPerm = null;
160       for (UserPermission perm : perms) {
161         if (Bytes.equals(perm.getUser(), userPerm.getUser())
162             && ((userPerm.isGlobal() && ACL_TABLE_NAME.equals(perm.getTableName()))
163                 || perm.tableFieldsEqual(userPerm))) {
164           currentPerm = perm;
165           break;
166         }
167       }
168 
169       if (currentPerm != null && currentPerm.getActions() != null) {
170         actionSet.addAll(Arrays.asList(currentPerm.getActions()));
171       }
172     }
173 
174     // merge current action with new action.
175     actionSet.addAll(Arrays.asList(actions));
176 
177     // serialize to byte array.
178     byte[] value = new byte[actionSet.size()];
179     int index = 0;
180     for (Permission.Action action : actionSet) {
181       value[index++] = action.code();
182     }
183 
184     p.addImmutable(ACL_LIST_FAMILY, key, value);
185     if (LOG.isDebugEnabled()) {
186       LOG.debug("Writing permission with rowKey " + Bytes.toString(rowKey) + " "
187           + Bytes.toString(key) + ": " + Bytes.toStringBinary(value));
188     }
189     if (t == null) {
190       try (Connection connection = ConnectionFactory.createConnection(conf)) {
191         try (Table table = connection.getTable(ACL_TABLE_NAME)) {
192           table.put(p);
193         }
194       }
195     } else {
196       try {
197         t.put(p);
198       } finally {
199         t.close();
200       }
201     }
202   }
203 
204   /**
205    * Stores a new user permission grant in the access control lists table.
206    * @param conf the configuration
207    * @param userPerm the details of the permission to be granted
208    * @param t acl table instance. It is closed upon method return
209    * @throws IOException in the case of an error accessing the metadata table
210    */
211   static void addUserPermission(Configuration conf, UserPermission userPerm, Table t)
212       throws IOException {
213     addUserPermission(conf, userPerm, t, false);
214   }
215 
216   /**
217    * Removes a previously granted permission from the stored access control
218    * lists.  The {@link TablePermission} being removed must exactly match what
219    * is stored -- no wildcard matching is attempted.  Ie, if user "bob" has
220    * been granted "READ" access to the "data" table, but only to column family
221    * plus qualifier "info:colA", then trying to call this method with only
222    * user "bob" and the table name "data" (but without specifying the
223    * column qualifier "info:colA") will have no effect.
224    *
225    * @param conf the configuration
226    * @param userPerm the details of the permission to be revoked
227    * @param t acl table
228    * @throws IOException if there is an error accessing the metadata table
229    */
230   static void removeUserPermission(Configuration conf, UserPermission userPerm, Table t)
231       throws IOException {
232     if (null == userPerm.getActions()) {
233       removePermissionRecord(conf, userPerm, t);
234     } else {
235       // Get all the global user permissions from the acl table
236       List<UserPermission> permsList = getUserPermissions(conf, userPermissionRowKey(userPerm));
237       List<Permission.Action> remainingActions = new ArrayList<>();
238       List<Permission.Action> dropActions = Arrays.asList(userPerm.getActions());
239       for (UserPermission perm : permsList) {
240         // Find the user and remove only the requested permissions
241         if (Bytes.toString(perm.getUser()).equals(Bytes.toString(userPerm.getUser()))) {
242           for (Permission.Action oldAction : perm.getActions()) {
243             if (!dropActions.contains(oldAction)) {
244               remainingActions.add(oldAction);
245             }
246           }
247           if (!remainingActions.isEmpty()) {
248             perm.setActions(remainingActions.toArray(new Permission.Action[remainingActions.size()]));
249             addUserPermission(conf, perm, t);
250           } else {
251             removePermissionRecord(conf, userPerm, t);
252           }
253           break;
254         }
255       }
256     }
257     if (LOG.isDebugEnabled()) {
258       LOG.debug("Removed permission "+ userPerm.toString());
259     }
260   }
261 
262   private static void removePermissionRecord(Configuration conf, UserPermission userPerm, Table t)
263       throws IOException {
264     Delete d = new Delete(userPermissionRowKey(userPerm));
265     d.addColumns(ACL_LIST_FAMILY, userPermissionKey(userPerm));
266     if (t == null) {
267       try (Connection connection = ConnectionFactory.createConnection(conf)) {
268         try (Table table = connection.getTable(ACL_TABLE_NAME)) {
269           table.delete(d);
270         }
271       }
272     } else {
273       try {
274         t.delete(d);
275       } finally {
276         t.close();
277       }
278     }
279   }
280 
281   /**
282    * Remove specified table from the _acl_ table.
283    */
284   static void removeTablePermissions(Configuration conf, TableName tableName, Table t)
285       throws IOException{
286     Delete d = new Delete(tableName.getName());
287 
288     if (LOG.isDebugEnabled()) {
289       LOG.debug("Removing permissions of removed table "+ tableName);
290     }
291     try {
292       t.delete(d);
293     } finally {
294       t.close();
295     }
296   }
297 
298   /**
299    * Remove specified namespace from the acl table.
300    */
301   static void removeNamespacePermissions(Configuration conf, String namespace, Table t)
302       throws IOException{
303     Delete d = new Delete(Bytes.toBytes(toNamespaceEntry(namespace)));
304 
305     if (LOG.isDebugEnabled()) {
306       LOG.debug("Removing permissions of removed namespace "+ namespace);
307     }
308 
309     try {
310       t.delete(d);
311     } finally {
312       t.close();
313     }
314   }
315 
316   /**
317    * Remove specified table column from the acl table.
318    */
319   static void removeTablePermissions(TableName tableName, byte[] column, Table table,
320       boolean closeTable) throws IOException{
321 
322     if (LOG.isDebugEnabled()) {
323       LOG.debug("Removing permissions of removed column " + Bytes.toString(column) +
324                 " from table "+ tableName);
325     }
326     Scan scan = new Scan();
327     scan.addFamily(ACL_LIST_FAMILY);
328 
329     String columnName = Bytes.toString(column);
330     scan.setFilter(new QualifierFilter(CompareOp.EQUAL, new RegexStringComparator(
331         String.format("(%s%s%s)|(%s%s)$",
332             ACL_KEY_DELIMITER, columnName, ACL_KEY_DELIMITER,
333             ACL_KEY_DELIMITER, columnName))));
334 
335     Set<byte[]> qualifierSet = new TreeSet<byte[]>(Bytes.BYTES_COMPARATOR);
336     ResultScanner scanner = null;
337     try {
338       scanner = table.getScanner(scan);
339       for (Result res : scanner) {
340         for (byte[] q : res.getFamilyMap(ACL_LIST_FAMILY).navigableKeySet()) {
341           qualifierSet.add(q);
342         }
343       }
344 
345       if (qualifierSet.size() > 0) {
346         Delete d = new Delete(tableName.getName());
347         for (byte[] qualifier : qualifierSet) {
348           d.addColumns(ACL_LIST_FAMILY, qualifier);
349         }
350         table.delete(d);
351       }
352     }  finally {
353       if (scanner != null) scanner.close();
354       if (closeTable) table.close();
355     }
356   }
357 
358   static void removeTablePermissions(Configuration conf, TableName tableName, byte[] column,
359       Table t) throws IOException {
360     if (LOG.isDebugEnabled()) {
361       LOG.debug("Removing permissions of removed column " + Bytes.toString(column) +
362           " from table "+ tableName);
363     }
364     removeTablePermissions(tableName, column, t, true);
365   }
366 
367   static byte[] userPermissionRowKey(UserPermission userPerm) {
368     byte[] row;
369     if(userPerm.hasNamespace()) {
370       row = Bytes.toBytes(toNamespaceEntry(userPerm.getNamespace()));
371     } else if(userPerm.isGlobal()) {
372       row = ACL_GLOBAL_NAME;
373     } else {
374       row = userPerm.getTableName().getName();
375     }
376     return row;
377   }
378 
379   /**
380    * Build qualifier key from user permission:
381    *  username
382    *  username,family
383    *  username,family,qualifier
384    */
385   static byte[] userPermissionKey(UserPermission userPerm) {
386     byte[] qualifier = userPerm.getQualifier();
387     byte[] family = userPerm.getFamily();
388     byte[] key = userPerm.getUser();
389 
390     if (family != null && family.length > 0) {
391       key = Bytes.add(key, Bytes.add(new byte[]{ACL_KEY_DELIMITER}, family));
392       if (qualifier != null && qualifier.length > 0) {
393         key = Bytes.add(key, Bytes.add(new byte[]{ACL_KEY_DELIMITER}, qualifier));
394       }
395     }
396 
397     return key;
398   }
399 
400   /**
401    * Returns {@code true} if the given region is part of the {@code _acl_}
402    * metadata table.
403    */
404   static boolean isAclRegion(Region region) {
405     return ACL_TABLE_NAME.equals(region.getTableDesc().getTableName());
406   }
407 
408   /**
409    * Returns {@code true} if the given table is {@code _acl_} metadata table.
410    */
411   static boolean isAclTable(HTableDescriptor desc) {
412     return ACL_TABLE_NAME.equals(desc.getTableName());
413   }
414 
415   /**
416    * Loads all of the permission grants stored in a region of the {@code _acl_}
417    * table.
418    *
419    * @param aclRegion
420    * @return a map of the permissions for this table.
421    * @throws IOException
422    */
423   static Map<byte[], ListMultimap<String,TablePermission>> loadAll(Region aclRegion)
424     throws IOException {
425 
426     if (!isAclRegion(aclRegion)) {
427       throw new IOException("Can only load permissions from "+ACL_TABLE_NAME);
428     }
429 
430     Map<byte[], ListMultimap<String, TablePermission>> allPerms =
431         new TreeMap<byte[], ListMultimap<String, TablePermission>>(Bytes.BYTES_RAWCOMPARATOR);
432 
433     // do a full scan of _acl_ table
434 
435     Scan scan = new Scan();
436     scan.addFamily(ACL_LIST_FAMILY);
437 
438     InternalScanner iScanner = null;
439     try {
440       iScanner = aclRegion.getScanner(scan);
441 
442       while (true) {
443         List<Cell> row = new ArrayList<Cell>();
444 
445         boolean hasNext = iScanner.next(row);
446         ListMultimap<String,TablePermission> perms = ArrayListMultimap.create();
447         byte[] entry = null;
448         for (Cell kv : row) {
449           if (entry == null) {
450             entry = CellUtil.cloneRow(kv);
451           }
452           Pair<String,TablePermission> permissionsOfUserOnTable =
453               parsePermissionRecord(entry, kv);
454           if (permissionsOfUserOnTable != null) {
455             String username = permissionsOfUserOnTable.getFirst();
456             TablePermission permissions = permissionsOfUserOnTable.getSecond();
457             perms.put(username, permissions);
458           }
459         }
460         if (entry != null) {
461           allPerms.put(entry, perms);
462         }
463         if (!hasNext) {
464           break;
465         }
466       }
467     } finally {
468       if (iScanner != null) {
469         iScanner.close();
470       }
471     }
472 
473     return allPerms;
474   }
475 
476   /**
477    * Load all permissions from the region server holding {@code _acl_},
478    * primarily intended for testing purposes.
479    */
480   static Map<byte[], ListMultimap<String,TablePermission>> loadAll(
481       Configuration conf) throws IOException {
482     Map<byte[], ListMultimap<String,TablePermission>> allPerms =
483         new TreeMap<byte[], ListMultimap<String,TablePermission>>(Bytes.BYTES_RAWCOMPARATOR);
484 
485     // do a full scan of _acl_, filtering on only first table region rows
486 
487     Scan scan = new Scan();
488     scan.addFamily(ACL_LIST_FAMILY);
489 
490     ResultScanner scanner = null;
491     // TODO: Pass in a Connection rather than create one each time.
492     try (Connection connection = ConnectionFactory.createConnection(conf)) {
493       try (Table table = connection.getTable(ACL_TABLE_NAME)) {
494         scanner = table.getScanner(scan);
495         try {
496           for (Result row : scanner) {
497             ListMultimap<String,TablePermission> resultPerms = parsePermissions(row.getRow(), row);
498             allPerms.put(row.getRow(), resultPerms);
499           }
500         } finally {
501           if (scanner != null) scanner.close();
502         }
503       }
504     }
505 
506     return allPerms;
507   }
508 
509   public static ListMultimap<String, TablePermission> getTablePermissions(Configuration conf,
510         TableName tableName) throws IOException {
511     return getPermissions(conf, tableName != null ? tableName.getName() : null, null);
512   }
513 
514   @VisibleForTesting
515   public static ListMultimap<String, TablePermission> getNamespacePermissions(Configuration conf,
516         String namespace) throws IOException {
517     return getPermissions(conf, Bytes.toBytes(toNamespaceEntry(namespace)), null);
518   }
519 
520   /**
521    * Reads user permission assignments stored in the <code>l:</code> column
522    * family of the first table row in <code>_acl_</code>.
523    *
524    * <p>
525    * See {@link AccessControlLists class documentation} for the key structure
526    * used for storage.
527    * </p>
528    */
529   static ListMultimap<String, TablePermission> getPermissions(Configuration conf,
530       byte[] entryName, Table t) throws IOException {
531     if (entryName == null) entryName = ACL_GLOBAL_NAME;
532 
533     // for normal user tables, we just read the table row from _acl_
534     ListMultimap<String, TablePermission> perms = ArrayListMultimap.create();
535     Get get = new Get(entryName);
536     get.addFamily(ACL_LIST_FAMILY);
537     Result row = null;
538     if (t == null) {
539       try (Connection connection = ConnectionFactory.createConnection(conf)) {
540         try (Table table = connection.getTable(ACL_TABLE_NAME)) {
541           row = table.get(get);
542         }
543       }
544     } else {
545       row = t.get(get);
546     }
547 
548     if (!row.isEmpty()) {
549       perms = parsePermissions(entryName, row);
550     } else {
551       LOG.info("No permissions found in " + ACL_TABLE_NAME + " for acl entry "
552           + Bytes.toString(entryName));
553     }
554 
555     return perms;
556   }
557 
558   /**
559    * Returns the currently granted permissions for a given table as a list of
560    * user plus associated permissions.
561    */
562   static List<UserPermission> getUserTablePermissions(
563       Configuration conf, TableName tableName) throws IOException {
564     return getUserPermissions(conf, tableName == null ? null : tableName.getName());
565   }
566 
567   static List<UserPermission> getUserNamespacePermissions(
568       Configuration conf, String namespace) throws IOException {
569     return getUserPermissions(conf, Bytes.toBytes(toNamespaceEntry(namespace)));
570   }
571 
572   static List<UserPermission> getUserPermissions(
573       Configuration conf, byte[] entryName)
574   throws IOException {
575     ListMultimap<String,TablePermission> allPerms = getPermissions(
576       conf, entryName, null);
577 
578     List<UserPermission> perms = new ArrayList<UserPermission>();
579 
580     if(isNamespaceEntry(entryName)) {  // Namespace
581       for (Map.Entry<String, TablePermission> entry : allPerms.entries()) {
582         UserPermission up = new UserPermission(Bytes.toBytes(entry.getKey()),
583           entry.getValue().getNamespace(), entry.getValue().getActions());
584         perms.add(up);
585       }
586     } else {  // Table
587       for (Map.Entry<String, TablePermission> entry : allPerms.entries()) {
588         UserPermission up = new UserPermission(Bytes.toBytes(entry.getKey()),
589             entry.getValue().getTableName(), entry.getValue().getFamily(),
590             entry.getValue().getQualifier(), entry.getValue().getActions());
591         perms.add(up);
592       }
593     }
594     return perms;
595   }
596 
597   private static ListMultimap<String, TablePermission> parsePermissions(
598       byte[] entryName, Result result) {
599     ListMultimap<String, TablePermission> perms = ArrayListMultimap.create();
600     if (result != null && result.size() > 0) {
601       for (Cell kv : result.rawCells()) {
602 
603         Pair<String,TablePermission> permissionsOfUserOnTable =
604             parsePermissionRecord(entryName, kv);
605 
606         if (permissionsOfUserOnTable != null) {
607           String username = permissionsOfUserOnTable.getFirst();
608           TablePermission permissions = permissionsOfUserOnTable.getSecond();
609           perms.put(username, permissions);
610         }
611       }
612     }
613     return perms;
614   }
615 
616   private static Pair<String, TablePermission> parsePermissionRecord(
617       byte[] entryName, Cell kv) {
618     // return X given a set of permissions encoded in the permissionRecord kv.
619     byte[] family = CellUtil.cloneFamily(kv);
620 
621     if (!Bytes.equals(family, ACL_LIST_FAMILY)) {
622       return null;
623     }
624 
625     byte[] key = CellUtil.cloneQualifier(kv);
626     byte[] value = CellUtil.cloneValue(kv);
627     if (LOG.isDebugEnabled()) {
628       LOG.debug("Read acl: kv ["+
629                 Bytes.toStringBinary(key)+": "+
630                 Bytes.toStringBinary(value)+"]");
631     }
632 
633     // check for a column family appended to the key
634     // TODO: avoid the string conversion to make this more efficient
635     String username = Bytes.toString(key);
636 
637     //Handle namespace entry
638     if(isNamespaceEntry(entryName)) {
639       return new Pair<String, TablePermission>(username,
640           new TablePermission(Bytes.toString(fromNamespaceEntry(entryName)), value));
641     }
642 
643     //Handle table and global entry
644     //TODO global entry should be handled differently
645     int idx = username.indexOf(ACL_KEY_DELIMITER);
646     byte[] permFamily = null;
647     byte[] permQualifier = null;
648     if (idx > 0 && idx < username.length()-1) {
649       String remainder = username.substring(idx+1);
650       username = username.substring(0, idx);
651       idx = remainder.indexOf(ACL_KEY_DELIMITER);
652       if (idx > 0 && idx < remainder.length()-1) {
653         permFamily = Bytes.toBytes(remainder.substring(0, idx));
654         permQualifier = Bytes.toBytes(remainder.substring(idx+1));
655       } else {
656         permFamily = Bytes.toBytes(remainder);
657       }
658     }
659 
660     return new Pair<String,TablePermission>(username,
661         new TablePermission(TableName.valueOf(entryName), permFamily, permQualifier, value));
662   }
663 
664   /**
665    * Writes a set of permissions as {@link org.apache.hadoop.io.Writable} instances
666    * and returns the resulting byte array.
667    *
668    * Writes a set of permission [user: table permission]
669    */
670   public static byte[] writePermissionsAsBytes(ListMultimap<String, TablePermission> perms,
671       Configuration conf) {
672     return ProtobufUtil.prependPBMagic(ProtobufUtil.toUserTablePermissions(perms).toByteArray());
673   }
674 
675   /**
676    * Reads a set of permissions as {@link org.apache.hadoop.io.Writable} instances
677    * from the input stream.
678    */
679   public static ListMultimap<String, TablePermission> readPermissions(byte[] data,
680       Configuration conf)
681   throws DeserializationException {
682     if (ProtobufUtil.isPBMagicPrefix(data)) {
683       int pblen = ProtobufUtil.lengthOfPBMagic();
684       try {
685         AccessControlProtos.UsersAndPermissions.Builder builder =
686           AccessControlProtos.UsersAndPermissions.newBuilder();
687         ProtobufUtil.mergeFrom(builder, data, pblen, data.length - pblen);
688         return ProtobufUtil.toUserTablePermissions(builder.build());
689       } catch (IOException e) {
690         throw new DeserializationException(e);
691       }
692     } else {
693       ListMultimap<String,TablePermission> perms = ArrayListMultimap.create();
694       try {
695         DataInput in = new DataInputStream(new ByteArrayInputStream(data));
696         int length = in.readInt();
697         for (int i=0; i<length; i++) {
698           String user = Text.readString(in);
699           List<TablePermission> userPerms =
700             (List)HbaseObjectWritableFor96Migration.readObject(in, conf);
701           perms.putAll(user, userPerms);
702         }
703       } catch (IOException e) {
704         throw new DeserializationException(e);
705       }
706       return perms;
707     }
708   }
709 
710   public static boolean isNamespaceEntry(String entryName) {
711     return entryName != null && entryName.charAt(0) == NAMESPACE_PREFIX;
712   }
713 
714   public static boolean isNamespaceEntry(byte[] entryName) {
715     return entryName != null && entryName.length !=0 && entryName[0] == NAMESPACE_PREFIX;
716   }
717 
718   public static String toNamespaceEntry(String namespace) {
719      return NAMESPACE_PREFIX + namespace;
720    }
721 
722    public static String fromNamespaceEntry(String namespace) {
723      if(namespace.charAt(0) != NAMESPACE_PREFIX)
724        throw new IllegalArgumentException("Argument is not a valid namespace entry");
725      return namespace.substring(1);
726    }
727 
728    public static byte[] toNamespaceEntry(byte[] namespace) {
729      byte[] ret = new byte[namespace.length+1];
730      ret[0] = NAMESPACE_PREFIX;
731      System.arraycopy(namespace, 0, ret, 1, namespace.length);
732      return ret;
733    }
734 
735    public static byte[] fromNamespaceEntry(byte[] namespace) {
736      if(namespace[0] != NAMESPACE_PREFIX) {
737        throw new IllegalArgumentException("Argument is not a valid namespace entry: " +
738            Bytes.toString(namespace));
739      }
740      return Arrays.copyOfRange(namespace, 1, namespace.length);
741    }
742 
743    public static List<Permission> getCellPermissionsForUser(User user, Cell cell)
744        throws IOException {
745      // Save an object allocation where we can
746      if (cell.getTagsLength() == 0) {
747        return null;
748      }
749      List<Permission> results = Lists.newArrayList();
750      Iterator<Tag> tagsIterator = CellUtil.tagsIterator(cell.getTagsArray(), cell.getTagsOffset(),
751         cell.getTagsLength());
752      while (tagsIterator.hasNext()) {
753        Tag tag = tagsIterator.next();
754        if (tag.getType() == ACL_TAG_TYPE) {
755          // Deserialize the table permissions from the KV
756          // TODO: This can be improved. Don't build UsersAndPermissions just to unpack it again,
757          // use the builder
758          AccessControlProtos.UsersAndPermissions.Builder builder = 
759            AccessControlProtos.UsersAndPermissions.newBuilder();
760          ProtobufUtil.mergeFrom(builder, tag.getBuffer(), tag.getTagOffset(), tag.getTagLength());
761          ListMultimap<String,Permission> kvPerms =
762            ProtobufUtil.toUsersAndPermissions(builder.build());
763          // Are there permissions for this user?
764          List<Permission> userPerms = kvPerms.get(user.getShortName());
765          if (userPerms != null) {
766            results.addAll(userPerms);
767          }
768          // Are there permissions for any of the groups this user belongs to?
769          String groupNames[] = user.getGroupNames();
770          if (groupNames != null) {
771            for (String group : groupNames) {
772              List<Permission> groupPerms = kvPerms.get(AuthUtil.toGroupEntry(group));
773              if (results != null) {
774                results.addAll(groupPerms);
775              }
776            }
777          }
778        }
779      }
780      return results;
781    }
782 }