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