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