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