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