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  package org.apache.hadoop.hbase.security.visibility;
19  
20  import static org.apache.hadoop.hbase.security.visibility.VisibilityConstants.LABELS_TABLE_NAME;
21  import static org.junit.Assert.assertArrayEquals;
22  import static org.junit.Assert.assertEquals;
23  import static org.junit.Assert.assertTrue;
24  
25  import java.io.IOException;
26  import java.security.PrivilegedExceptionAction;
27  import java.util.ArrayList;
28  import java.util.List;
29  import java.util.concurrent.atomic.AtomicInteger;
30  
31  import org.apache.commons.logging.Log;
32  import org.apache.commons.logging.LogFactory;
33  import org.apache.hadoop.conf.Configuration;
34  import org.apache.hadoop.hbase.Cell;
35  import org.apache.hadoop.hbase.CellScanner;
36  import org.apache.hadoop.hbase.CellUtil;
37  import org.apache.hadoop.hbase.HBaseConfiguration;
38  import org.apache.hadoop.hbase.HBaseTestingUtility;
39  import org.apache.hadoop.hbase.HColumnDescriptor;
40  import org.apache.hadoop.hbase.HConstants;
41  import org.apache.hadoop.hbase.HTableDescriptor;
42  import org.apache.hadoop.hbase.KeyValue;
43  import org.apache.hadoop.hbase.KeyValueUtil;
44  import org.apache.hadoop.hbase.testclassification.MediumTests;
45  import org.apache.hadoop.hbase.TableName;
46  import org.apache.hadoop.hbase.Tag;
47  import org.apache.hadoop.hbase.TagRewriteCell;
48  import org.apache.hadoop.hbase.TagType;
49  import org.apache.hadoop.hbase.client.Connection;
50  import org.apache.hadoop.hbase.client.ConnectionFactory;
51  import org.apache.hadoop.hbase.client.Durability;
52  import org.apache.hadoop.hbase.client.Get;
53  import org.apache.hadoop.hbase.client.HBaseAdmin;
54  import org.apache.hadoop.hbase.client.Put;
55  import org.apache.hadoop.hbase.client.Result;
56  import org.apache.hadoop.hbase.client.ResultScanner;
57  import org.apache.hadoop.hbase.client.Scan;
58  import org.apache.hadoop.hbase.client.Table;
59  import org.apache.hadoop.hbase.client.replication.ReplicationAdmin;
60  import org.apache.hadoop.hbase.codec.KeyValueCodecWithTags;
61  import org.apache.hadoop.hbase.coprocessor.BaseRegionObserver;
62  import org.apache.hadoop.hbase.coprocessor.CoprocessorHost;
63  import org.apache.hadoop.hbase.coprocessor.ObserverContext;
64  import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment;
65  import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.VisibilityLabelsResponse;
66  import org.apache.hadoop.hbase.regionserver.wal.WALEdit;
67  import org.apache.hadoop.hbase.replication.ReplicationEndpoint;
68  import org.apache.hadoop.hbase.replication.ReplicationPeerConfig;
69  import org.apache.hadoop.hbase.security.User;
70  import org.apache.hadoop.hbase.security.visibility.VisibilityController.VisibilityReplication;
71  import org.junit.experimental.categories.Category;
72  import org.apache.hadoop.hbase.util.Bytes;
73  import org.apache.hadoop.hbase.wal.WAL.Entry;
74  import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster;
75  import org.apache.hadoop.hbase.zookeeper.ZooKeeperWatcher;
76  import org.junit.Assert;
77  import org.junit.Before;
78  import org.junit.Rule;
79  import org.junit.Test;
80  import org.junit.rules.TestName;
81  
82  @Category(MediumTests.class)
83  public class TestVisibilityLabelsReplication {
84    private static final Log LOG = LogFactory.getLog(TestVisibilityLabelsReplication.class);
85    protected static final int NON_VIS_TAG_TYPE = 100;
86    protected static final String TEMP = "temp";
87    protected static Configuration conf;
88    protected static Configuration conf1;
89    protected static String TABLE_NAME = "TABLE_NAME";
90    protected static byte[] TABLE_NAME_BYTES = Bytes.toBytes(TABLE_NAME);
91    protected static ReplicationAdmin replicationAdmin;
92    public static final String TOPSECRET = "topsecret";
93    public static final String PUBLIC = "public";
94    public static final String PRIVATE = "private";
95    public static final String CONFIDENTIAL = "confidential";
96    public static final String COPYRIGHT = "\u00A9ABC";
97    public static final String ACCENT = "\u0941";
98    public static final String SECRET = "secret";
99    public static final String UNICODE_VIS_TAG = COPYRIGHT + "\"" + ACCENT + "\\" + SECRET + "\""
100       + "\u0027&\\";
101   public static HBaseTestingUtility TEST_UTIL;
102   public static HBaseTestingUtility TEST_UTIL1;
103   public static final byte[] row1 = Bytes.toBytes("row1");
104   public static final byte[] row2 = Bytes.toBytes("row2");
105   public static final byte[] row3 = Bytes.toBytes("row3");
106   public static final byte[] row4 = Bytes.toBytes("row4");
107   public final static byte[] fam = Bytes.toBytes("info");
108   public final static byte[] qual = Bytes.toBytes("qual");
109   public final static byte[] value = Bytes.toBytes("value");
110   protected static ZooKeeperWatcher zkw1;
111   protected static ZooKeeperWatcher zkw2;
112   protected static int expected[] = { 4, 6, 4, 0, 3 };
113   private static final String NON_VISIBILITY = "non-visibility";
114   protected static String[] expectedVisString = {
115       "(\"secret\"&\"topsecret\"&\"public\")|(\"topsecret\"&\"confidential\")",
116       "(\"public\"&\"private\")|(\"topsecret\"&\"private\")|"
117           + "(\"confidential\"&\"public\")|(\"topsecret\"&\"confidential\")",
118       "(!\"topsecret\"&\"secret\")|(!\"topsecret\"&\"confidential\")",
119       "(\"secret\"&\"" + COPYRIGHT + "\\\"" + ACCENT + "\\\\" + SECRET + "\\\"" + "\u0027&\\\\"
120           + "\")" };
121 
122   @Rule
123   public final TestName TEST_NAME = new TestName();
124   public static User SUPERUSER, USER1;
125 
126   @Before
127   public void setup() throws Exception {
128     // setup configuration
129     conf = HBaseConfiguration.create();
130     conf.setBoolean(HConstants.DISTRIBUTED_LOG_REPLAY_KEY, false);
131     conf.setBoolean("hbase.online.schema.update.enable", true);
132     conf.setInt("hfile.format.version", 3);
133     conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/1");
134     conf.setInt("replication.source.size.capacity", 10240);
135     conf.setLong("replication.source.sleepforretries", 100);
136     conf.setInt("hbase.regionserver.maxlogs", 10);
137     conf.setLong("hbase.master.logcleaner.ttl", 10);
138     conf.setInt("zookeeper.recovery.retry", 1);
139     conf.setInt("zookeeper.recovery.retry.intervalmill", 10);
140     conf.setBoolean("dfs.support.append", true);
141     conf.setLong(HConstants.THREAD_WAKE_FREQUENCY, 100);
142     conf.setInt("replication.stats.thread.period.seconds", 5);
143     conf.setBoolean("hbase.tests.use.shortcircuit.reads", false);
144     setVisibilityLabelServiceImpl(conf);
145     conf.setBoolean(HConstants.REPLICATION_ENABLE_KEY, HConstants.REPLICATION_ENABLE_DEFAULT);
146     conf.setStrings(HConstants.REPLICATION_CODEC_CONF_KEY, KeyValueCodecWithTags.class.getName());
147     VisibilityTestUtil.enableVisiblityLabels(conf);
148     conf.set(CoprocessorHost.REGIONSERVER_COPROCESSOR_CONF_KEY,
149         VisibilityReplication.class.getName());
150     conf.setStrings(CoprocessorHost.USER_REGION_COPROCESSOR_CONF_KEY,
151         SimpleCP.class.getName());
152     // Have to reset conf1 in case zk cluster location different
153     // than default
154     conf.setClass(VisibilityUtils.VISIBILITY_LABEL_GENERATOR_CLASS, SimpleScanLabelGenerator.class,
155         ScanLabelGenerator.class);
156     conf.set("hbase.superuser", User.getCurrent().getShortName());
157     SUPERUSER = User.createUserForTesting(conf, User.getCurrent().getShortName(),
158         new String[] { "supergroup" });
159     // User.createUserForTesting(conf, User.getCurrent().getShortName(), new
160     // String[] { "supergroup" });
161     USER1 = User.createUserForTesting(conf, "user1", new String[] {});
162     TEST_UTIL = new HBaseTestingUtility(conf);
163     TEST_UTIL.startMiniZKCluster();
164     MiniZooKeeperCluster miniZK = TEST_UTIL.getZkCluster();
165     zkw1 = new ZooKeeperWatcher(conf, "cluster1", null, true);
166     replicationAdmin = new ReplicationAdmin(conf);
167 
168     // Base conf2 on conf1 so it gets the right zk cluster.
169     conf1 = HBaseConfiguration.create(conf);
170     conf1.setInt("hfile.format.version", 3);
171     conf1.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/2");
172     conf1.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 6);
173     conf1.setBoolean("dfs.support.append", true);
174     conf1.setBoolean("hbase.tests.use.shortcircuit.reads", false);
175     conf.setBoolean(HConstants.REPLICATION_ENABLE_KEY, HConstants.REPLICATION_ENABLE_DEFAULT);
176     conf1.setStrings(HConstants.REPLICATION_CODEC_CONF_KEY, KeyValueCodecWithTags.class.getName());
177     conf1.setStrings(CoprocessorHost.USER_REGION_COPROCESSOR_CONF_KEY,
178         TestCoprocessorForTagsAtSink.class.getName());
179     // setVisibilityLabelServiceImpl(conf1);
180     USER1 = User.createUserForTesting(conf1, "user1", new String[] {});
181     TEST_UTIL1 = new HBaseTestingUtility(conf1);
182     TEST_UTIL1.setZkCluster(miniZK);
183     zkw2 = new ZooKeeperWatcher(conf1, "cluster2", null, true);
184     ReplicationPeerConfig rpc = new ReplicationPeerConfig();
185     rpc.setClusterKey(TEST_UTIL1.getClusterKey());
186     replicationAdmin.addPeer("2", rpc);
187 
188     TEST_UTIL.startMiniCluster(1);
189     // Wait for the labels table to become available
190     TEST_UTIL.waitTableEnabled(LABELS_TABLE_NAME.getName(), 50000);
191     TEST_UTIL1.startMiniCluster(1);
192     HBaseAdmin hBaseAdmin = TEST_UTIL.getHBaseAdmin();
193     HTableDescriptor table = new HTableDescriptor(TableName.valueOf(TABLE_NAME));
194     HColumnDescriptor desc = new HColumnDescriptor(fam);
195     desc.setScope(HConstants.REPLICATION_SCOPE_GLOBAL);
196     table.addFamily(desc);
197     try {
198       hBaseAdmin.createTable(table);
199     } finally {
200       if (hBaseAdmin != null) {
201         hBaseAdmin.close();
202       }
203     }
204     HBaseAdmin hBaseAdmin1 = TEST_UTIL1.getHBaseAdmin();
205     try {
206       hBaseAdmin1.createTable(table);
207     } finally {
208       if (hBaseAdmin1 != null) {
209         hBaseAdmin1.close();
210       }
211     }
212     addLabels();
213     setAuths(conf);
214     setAuths(conf1);
215   }
216 
217   protected static void setVisibilityLabelServiceImpl(Configuration conf) {
218     conf.setClass(VisibilityLabelServiceManager.VISIBILITY_LABEL_SERVICE_CLASS,
219         DefaultVisibilityLabelServiceImpl.class, VisibilityLabelService.class);
220   }
221 
222   @Test
223   public void testVisibilityReplication() throws Exception {
224     int retry = 0;
225     try (Table table = writeData(TableName.valueOf(TABLE_NAME),
226          "(" + SECRET + "&" + PUBLIC + ")" + "|(" + CONFIDENTIAL
227          + ")&(" + TOPSECRET + ")", "(" + PRIVATE + "|" + CONFIDENTIAL + ")&(" + PUBLIC + "|"
228          + TOPSECRET + ")", "(" + SECRET + "|" + CONFIDENTIAL + ")" + "&" + "!" + TOPSECRET,
229         CellVisibility.quote(UNICODE_VIS_TAG) + "&" + SECRET);) {
230       Scan s = new Scan();
231       s.setAuthorizations(new Authorizations(SECRET, CONFIDENTIAL, PRIVATE, TOPSECRET,
232           UNICODE_VIS_TAG));
233       ResultScanner scanner = table.getScanner(s);
234       Result[] next = scanner.next(4);
235 
236       assertTrue(next.length == 4);
237       CellScanner cellScanner = next[0].cellScanner();
238       cellScanner.advance();
239       Cell current = cellScanner.current();
240       assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(),
241           current.getRowLength(), row1, 0, row1.length));
242       cellScanner = next[1].cellScanner();
243       cellScanner.advance();
244       current = cellScanner.current();
245       assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(),
246           current.getRowLength(), row2, 0, row2.length));
247       cellScanner = next[2].cellScanner();
248       cellScanner.advance();
249       current = cellScanner.current();
250       assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(),
251           current.getRowLength(), row3, 0, row3.length));
252       cellScanner = next[3].cellScanner();
253       cellScanner.advance();
254       current = cellScanner.current();
255       assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(),
256           current.getRowLength(), row4, 0, row4.length));
257       try (Table table2 = TEST_UTIL1.getConnection().getTable(TableName.valueOf(TABLE_NAME))) {
258         s = new Scan();
259         // Ensure both rows are replicated
260         scanner = table2.getScanner(s);
261         next = scanner.next(4);
262         while (next.length == 0 && retry <= 10) {
263           scanner = table2.getScanner(s);
264           next = scanner.next(4);
265           Thread.sleep(2000);
266           retry++;
267         }
268         assertTrue(next.length == 4);
269         verifyGet(row1, expectedVisString[0], expected[0], false, TOPSECRET, CONFIDENTIAL);
270         TestCoprocessorForTagsAtSink.tags.clear();
271         verifyGet(row2, expectedVisString[1], expected[1], false, CONFIDENTIAL, PUBLIC);
272         TestCoprocessorForTagsAtSink.tags.clear();
273         verifyGet(row3, expectedVisString[2], expected[2], false, PRIVATE, SECRET);
274         verifyGet(row3, "", expected[3], true, TOPSECRET, SECRET);
275         verifyGet(row4, expectedVisString[3], expected[4], false, UNICODE_VIS_TAG, SECRET);
276       }
277     }
278   }
279 
280   protected static void doAssert(byte[] row, String visTag) throws Exception {
281     if (VisibilityReplicationEndPointForTest.lastEntries == null) {
282       return; // first call
283     }
284     Assert.assertEquals(1, VisibilityReplicationEndPointForTest.lastEntries.size());
285     List<Cell> cells = VisibilityReplicationEndPointForTest.lastEntries.get(0).getEdit().getCells();
286     Assert.assertEquals(4, cells.size());
287     boolean tagFound = false;
288     for (Cell cell : cells) {
289       if ((Bytes.equals(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), row, 0,
290           row.length))) {
291         List<Tag> tags = Tag
292             .asList(cell.getTagsArray(), cell.getTagsOffset(), cell.getTagsLength());
293         for (Tag tag : tags) {
294           if (tag.getType() == TagType.STRING_VIS_TAG_TYPE) {
295             assertEquals(visTag, Bytes.toString(tag.getValue()));
296             tagFound = true;
297             break;
298           }
299         }
300       }
301     }
302     assertTrue(tagFound);
303   }
304 
305   protected void verifyGet(final byte[] row, final String visString, final int expected,
306       final boolean nullExpected, final String... auths) throws IOException,
307       InterruptedException {
308     PrivilegedExceptionAction<Void> scanAction = new PrivilegedExceptionAction<Void>() {
309       public Void run() throws Exception {
310         try (Connection connection = ConnectionFactory.createConnection(conf1);
311              Table table2 = connection.getTable(TableName.valueOf(TABLE_NAME))) {
312           CellScanner cellScanner;
313           Cell current;
314           Get get = new Get(row);
315           get.setAuthorizations(new Authorizations(auths));
316           Result result = table2.get(get);
317           cellScanner = result.cellScanner();
318           boolean advance = cellScanner.advance();
319           if (nullExpected) {
320             assertTrue(!advance);
321             return null;
322           }
323           current = cellScanner.current();
324           assertArrayEquals(CellUtil.cloneRow(current), row);
325           for (Tag tag : TestCoprocessorForTagsAtSink.tags) {
326             LOG.info("The tag type is " + tag.getType());
327           }
328           assertEquals(expected, TestCoprocessorForTagsAtSink.tags.size());
329           Tag tag = TestCoprocessorForTagsAtSink.tags.get(1);
330           if (tag.getType() != NON_VIS_TAG_TYPE) {
331             assertEquals(TagType.VISIBILITY_EXP_SERIALIZATION_FORMAT_TAG_TYPE, tag.getType());
332           }
333           tag = TestCoprocessorForTagsAtSink.tags.get(0);
334           boolean foundNonVisTag = false;
335           for (Tag t : TestCoprocessorForTagsAtSink.tags) {
336             if (t.getType() == NON_VIS_TAG_TYPE) {
337               assertEquals(TEMP, Bytes.toString(t.getValue()));
338               foundNonVisTag = true;
339               break;
340             }
341           }
342           doAssert(row, visString);
343           assertTrue(foundNonVisTag);
344           return null;
345         }
346       }
347     };
348     USER1.runAs(scanAction);
349   }
350 
351   public static void addLabels() throws Exception {
352     PrivilegedExceptionAction<VisibilityLabelsResponse> action =
353         new PrivilegedExceptionAction<VisibilityLabelsResponse>() {
354       public VisibilityLabelsResponse run() throws Exception {
355         String[] labels = { SECRET, TOPSECRET, CONFIDENTIAL, PUBLIC, PRIVATE, UNICODE_VIS_TAG };
356         try (Connection conn = ConnectionFactory.createConnection(conf)) {
357           VisibilityClient.addLabels(conn, labels);
358         } catch (Throwable t) {
359           throw new IOException(t);
360         }
361         return null;
362       }
363     };
364     SUPERUSER.runAs(action);
365   }
366 
367   public static void setAuths(final Configuration conf) throws Exception {
368     PrivilegedExceptionAction<VisibilityLabelsResponse> action =
369         new PrivilegedExceptionAction<VisibilityLabelsResponse>() {
370       public VisibilityLabelsResponse run() throws Exception {
371         try (Connection conn = ConnectionFactory.createConnection(conf)) {
372           return VisibilityClient.setAuths(conn, new String[] { SECRET,
373             CONFIDENTIAL, PRIVATE, TOPSECRET, UNICODE_VIS_TAG }, "user1");
374         } catch (Throwable e) {
375           throw new Exception(e);
376         }
377       }
378     };
379     VisibilityLabelsResponse response = SUPERUSER.runAs(action);
380   }
381 
382   static Table writeData(TableName tableName, String... labelExps) throws Exception {
383     Table table = TEST_UTIL.getConnection().getTable(TableName.valueOf(TABLE_NAME));
384     int i = 1;
385     List<Put> puts = new ArrayList<Put>();
386     for (String labelExp : labelExps) {
387       Put put = new Put(Bytes.toBytes("row" + i));
388       put.add(fam, qual, HConstants.LATEST_TIMESTAMP, value);
389       put.setCellVisibility(new CellVisibility(labelExp));
390       put.setAttribute(NON_VISIBILITY, Bytes.toBytes(TEMP));
391       puts.add(put);
392       i++;
393     }
394     table.put(puts);
395     return table;
396   }
397   // A simple BaseRegionbserver impl that allows to add a non-visibility tag from the
398   // attributes of the Put mutation.  The existing cells in the put mutation is overwritten
399   // with a new cell that has the visibility tags and the non visibility tag
400   public static class SimpleCP extends BaseRegionObserver {
401     @Override
402     public void prePut(ObserverContext<RegionCoprocessorEnvironment> e, Put m, WALEdit edit,
403         Durability durability) throws IOException {
404       byte[] attribute = m.getAttribute(NON_VISIBILITY);
405       byte[] cf = null;
406       List<Cell> updatedCells = new ArrayList<Cell>();
407       if (attribute != null) {
408         for (List<? extends Cell> edits : m.getFamilyCellMap().values()) {
409           for (Cell cell : edits) {
410             KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
411             if (cf == null) {
412               cf = kv.getFamily();
413             }
414             Tag tag = new Tag((byte) NON_VIS_TAG_TYPE, attribute);
415             List<Tag> tagList = new ArrayList<Tag>();
416             tagList.add(tag);
417             tagList.addAll(kv.getTags());
418             byte[] fromList = Tag.fromList(tagList);
419             TagRewriteCell newcell = new TagRewriteCell(kv, fromList);
420             KeyValue newKV = new KeyValue(kv.getRow(), 0, kv.getRowLength(), kv.getFamily(), 0,
421                 kv.getFamilyLength(), kv.getQualifier(), 0, kv.getQualifierLength(),
422                 kv.getTimestamp(), KeyValue.Type.codeToType(kv.getType()), kv.getValue(), 0,
423                 kv.getValueLength(), tagList);
424             ((List<Cell>) updatedCells).add(newcell);
425           }
426         }
427         m.getFamilyCellMap().remove(cf);
428         // Update the family map
429         m.getFamilyCellMap().put(cf, updatedCells);
430       }
431     }
432   }
433 
434   public static class TestCoprocessorForTagsAtSink extends BaseRegionObserver {
435     public static List<Tag> tags = null;
436 
437     @Override
438     public void postGetOp(ObserverContext<RegionCoprocessorEnvironment> e, Get get,
439         List<Cell> results) throws IOException {
440       if (results.size() > 0) {
441         // Check tag presence in the 1st cell in 1st Result
442         if (!results.isEmpty()) {
443           Cell cell = results.get(0);
444           tags = Tag.asList(cell.getTagsArray(), cell.getTagsOffset(), cell.getTagsLength());
445         }
446       }
447     }
448   }
449 
450   /**
451    * An extn of VisibilityReplicationEndpoint to verify the tags that are replicated
452    */
453   public static class VisibilityReplicationEndPointForTest extends VisibilityReplicationEndpoint {
454     static AtomicInteger replicateCount = new AtomicInteger();
455     static volatile List<Entry> lastEntries = null;
456 
457     public VisibilityReplicationEndPointForTest(ReplicationEndpoint endpoint,
458         VisibilityLabelService visibilityLabelsService) {
459       super(endpoint, visibilityLabelsService);
460     }
461 
462     @Override
463     public boolean replicate(ReplicateContext replicateContext) {
464       boolean ret = super.replicate(replicateContext);
465       lastEntries = replicateContext.getEntries();
466       replicateCount.incrementAndGet();
467       return ret;
468     }
469   }
470 }