001/* 002 * Licensed to the Apache Software Foundation (ASF) under one 003 * or more contributor license agreements. See the NOTICE file 004 * distributed with this work for additional information 005 * regarding copyright ownership. The ASF licenses this file 006 * to you under the Apache License, Version 2.0 (the 007 * "License"); you may not use this file except in compliance 008 * with the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018package org.apache.hadoop.hbase.security.visibility; 019 020import static org.apache.hadoop.hbase.security.visibility.VisibilityConstants.LABELS_TABLE_NAME; 021import static org.junit.Assert.assertArrayEquals; 022import static org.junit.Assert.assertEquals; 023import static org.junit.Assert.assertTrue; 024 025import java.io.IOException; 026import java.security.PrivilegedExceptionAction; 027import java.util.ArrayList; 028import java.util.List; 029import java.util.Optional; 030import java.util.concurrent.atomic.AtomicInteger; 031import org.apache.hadoop.conf.Configuration; 032import org.apache.hadoop.hbase.ArrayBackedTag; 033import org.apache.hadoop.hbase.Cell; 034import org.apache.hadoop.hbase.CellScanner; 035import org.apache.hadoop.hbase.CellUtil; 036import org.apache.hadoop.hbase.HBaseClassTestRule; 037import org.apache.hadoop.hbase.HBaseConfiguration; 038import org.apache.hadoop.hbase.HBaseTestingUtility; 039import org.apache.hadoop.hbase.HColumnDescriptor; 040import org.apache.hadoop.hbase.HConstants; 041import org.apache.hadoop.hbase.HTableDescriptor; 042import org.apache.hadoop.hbase.KeyValue; 043import org.apache.hadoop.hbase.KeyValueUtil; 044import org.apache.hadoop.hbase.PrivateCellUtil; 045import org.apache.hadoop.hbase.TableName; 046import org.apache.hadoop.hbase.Tag; 047import org.apache.hadoop.hbase.TagType; 048import org.apache.hadoop.hbase.client.Admin; 049import org.apache.hadoop.hbase.client.Connection; 050import org.apache.hadoop.hbase.client.ConnectionFactory; 051import org.apache.hadoop.hbase.client.Durability; 052import org.apache.hadoop.hbase.client.Get; 053import org.apache.hadoop.hbase.client.Put; 054import org.apache.hadoop.hbase.client.Result; 055import org.apache.hadoop.hbase.client.ResultScanner; 056import org.apache.hadoop.hbase.client.Scan; 057import org.apache.hadoop.hbase.client.Table; 058import org.apache.hadoop.hbase.codec.KeyValueCodecWithTags; 059import org.apache.hadoop.hbase.coprocessor.CoprocessorHost; 060import org.apache.hadoop.hbase.coprocessor.ObserverContext; 061import org.apache.hadoop.hbase.coprocessor.RegionCoprocessor; 062import org.apache.hadoop.hbase.coprocessor.RegionCoprocessorEnvironment; 063import org.apache.hadoop.hbase.coprocessor.RegionObserver; 064import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.VisibilityLabelsResponse; 065import org.apache.hadoop.hbase.replication.ReplicationEndpoint; 066import org.apache.hadoop.hbase.replication.ReplicationPeerConfig; 067import org.apache.hadoop.hbase.security.User; 068import org.apache.hadoop.hbase.testclassification.MediumTests; 069import org.apache.hadoop.hbase.testclassification.SecurityTests; 070import org.apache.hadoop.hbase.util.Bytes; 071import org.apache.hadoop.hbase.wal.WAL.Entry; 072import org.apache.hadoop.hbase.wal.WALEdit; 073import org.apache.hadoop.hbase.zookeeper.MiniZooKeeperCluster; 074import org.apache.hadoop.hbase.zookeeper.ZKWatcher; 075import org.junit.Assert; 076import org.junit.Before; 077import org.junit.ClassRule; 078import org.junit.Rule; 079import org.junit.Test; 080import org.junit.experimental.categories.Category; 081import org.junit.rules.TestName; 082import org.slf4j.Logger; 083import org.slf4j.LoggerFactory; 084 085@Category({ SecurityTests.class, MediumTests.class }) 086public class TestVisibilityLabelsReplication { 087 088 @ClassRule 089 public static final HBaseClassTestRule CLASS_RULE = 090 HBaseClassTestRule.forClass(TestVisibilityLabelsReplication.class); 091 092 private static final Logger LOG = LoggerFactory.getLogger(TestVisibilityLabelsReplication.class); 093 protected static final int NON_VIS_TAG_TYPE = 100; 094 protected static final String TEMP = "temp"; 095 protected static Configuration conf; 096 protected static Configuration conf1; 097 protected static TableName TABLE_NAME = TableName.valueOf("TABLE_NAME"); 098 protected static Admin admin; 099 public static final String TOPSECRET = "topsecret"; 100 public static final String PUBLIC = "public"; 101 public static final String PRIVATE = "private"; 102 public static final String CONFIDENTIAL = "confidential"; 103 public static final String COPYRIGHT = "\u00A9ABC"; 104 public static final String ACCENT = "\u0941"; 105 public static final String SECRET = "secret"; 106 public static final String UNICODE_VIS_TAG = 107 COPYRIGHT + "\"" + ACCENT + "\\" + SECRET + "\"" + "\u0027&\\"; 108 public static HBaseTestingUtility TEST_UTIL; 109 public static HBaseTestingUtility TEST_UTIL1; 110 public static final byte[] row1 = Bytes.toBytes("row1"); 111 public static final byte[] row2 = Bytes.toBytes("row2"); 112 public static final byte[] row3 = Bytes.toBytes("row3"); 113 public static final byte[] row4 = Bytes.toBytes("row4"); 114 public final static byte[] fam = Bytes.toBytes("info"); 115 public final static byte[] qual = Bytes.toBytes("qual"); 116 public final static byte[] value = Bytes.toBytes("value"); 117 protected static ZKWatcher zkw1; 118 protected static ZKWatcher zkw2; 119 protected static int expected[] = { 4, 6, 4, 0, 3 }; 120 private static final String NON_VISIBILITY = "non-visibility"; 121 protected static String[] expectedVisString = 122 { "(\"secret\"&\"topsecret\"&\"public\")|(\"topsecret\"&\"confidential\")", 123 "(\"public\"&\"private\")|(\"topsecret\"&\"private\")|" 124 + "(\"confidential\"&\"public\")|(\"topsecret\"&\"confidential\")", 125 "(!\"topsecret\"&\"secret\")|(!\"topsecret\"&\"confidential\")", "(\"secret\"&\"" + COPYRIGHT 126 + "\\\"" + ACCENT + "\\\\" + SECRET + "\\\"" + "\u0027&\\\\" + "\")" }; 127 128 @Rule 129 public final TestName TEST_NAME = new TestName(); 130 public static User SUPERUSER, USER1; 131 132 @Before 133 public void setup() throws Exception { 134 // setup configuration 135 conf = HBaseConfiguration.create(); 136 conf.setInt("hfile.format.version", 3); 137 conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/1"); 138 conf.setInt("replication.source.size.capacity", 10240); 139 conf.setLong("replication.source.sleepforretries", 100); 140 conf.setInt("hbase.regionserver.maxlogs", 10); 141 conf.setLong("hbase.master.logcleaner.ttl", 10); 142 conf.setInt("zookeeper.recovery.retry", 1); 143 conf.setInt("zookeeper.recovery.retry.intervalmill", 10); 144 conf.setLong(HConstants.THREAD_WAKE_FREQUENCY, 100); 145 conf.setInt("replication.stats.thread.period.seconds", 5); 146 conf.setBoolean("hbase.tests.use.shortcircuit.reads", false); 147 setVisibilityLabelServiceImpl(conf); 148 conf.setStrings(HConstants.REPLICATION_CODEC_CONF_KEY, KeyValueCodecWithTags.class.getName()); 149 VisibilityTestUtil.enableVisiblityLabels(conf); 150 conf.set(CoprocessorHost.REGIONSERVER_COPROCESSOR_CONF_KEY, 151 VisibilityReplication.class.getName()); 152 conf.setStrings(CoprocessorHost.USER_REGION_COPROCESSOR_CONF_KEY, SimpleCP.class.getName()); 153 // Have to reset conf1 in case zk cluster location different 154 // than default 155 conf.setClass(VisibilityUtils.VISIBILITY_LABEL_GENERATOR_CLASS, SimpleScanLabelGenerator.class, 156 ScanLabelGenerator.class); 157 conf.set("hbase.superuser", User.getCurrent().getShortName()); 158 SUPERUSER = User.createUserForTesting(conf, User.getCurrent().getShortName(), 159 new String[] { "supergroup" }); 160 // User.createUserForTesting(conf, User.getCurrent().getShortName(), new 161 // String[] { "supergroup" }); 162 USER1 = User.createUserForTesting(conf, "user1", new String[] {}); 163 TEST_UTIL = new HBaseTestingUtility(conf); 164 TEST_UTIL.startMiniZKCluster(); 165 MiniZooKeeperCluster miniZK = TEST_UTIL.getZkCluster(); 166 zkw1 = new ZKWatcher(conf, "cluster1", null, true); 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("hbase.tests.use.shortcircuit.reads", false); 174 conf1.setStrings(HConstants.REPLICATION_CODEC_CONF_KEY, KeyValueCodecWithTags.class.getName()); 175 conf1.setStrings(CoprocessorHost.USER_REGION_COPROCESSOR_CONF_KEY, 176 TestCoprocessorForTagsAtSink.class.getName()); 177 // setVisibilityLabelServiceImpl(conf1); 178 USER1 = User.createUserForTesting(conf1, "user1", new String[] {}); 179 TEST_UTIL1 = new HBaseTestingUtility(conf1); 180 TEST_UTIL1.setZkCluster(miniZK); 181 zkw2 = new ZKWatcher(conf1, "cluster2", null, true); 182 183 TEST_UTIL.startMiniCluster(1); 184 admin = TEST_UTIL.getAdmin(); 185 // Wait for the labels table to become available 186 TEST_UTIL.waitTableEnabled(LABELS_TABLE_NAME.getName(), 50000); 187 TEST_UTIL1.startMiniCluster(1); 188 189 ReplicationPeerConfig rpc = new ReplicationPeerConfig(); 190 rpc.setClusterKey(TEST_UTIL1.getClusterKey()); 191 admin.addReplicationPeer("2", rpc); 192 193 Admin hBaseAdmin = TEST_UTIL.getAdmin(); 194 HTableDescriptor table = new HTableDescriptor(TABLE_NAME); 195 HColumnDescriptor desc = new HColumnDescriptor(fam); 196 desc.setScope(HConstants.REPLICATION_SCOPE_GLOBAL); 197 table.addFamily(desc); 198 try { 199 hBaseAdmin.createTable(table); 200 } finally { 201 if (hBaseAdmin != null) { 202 hBaseAdmin.close(); 203 } 204 } 205 Admin hBaseAdmin1 = TEST_UTIL1.getAdmin(); 206 try { 207 hBaseAdmin1.createTable(table); 208 } finally { 209 if (hBaseAdmin1 != null) { 210 hBaseAdmin1.close(); 211 } 212 } 213 addLabels(); 214 setAuths(conf); 215 setAuths(conf1); 216 } 217 218 protected static void setVisibilityLabelServiceImpl(Configuration conf) { 219 conf.setClass(VisibilityLabelServiceManager.VISIBILITY_LABEL_SERVICE_CLASS, 220 DefaultVisibilityLabelServiceImpl.class, VisibilityLabelService.class); 221 } 222 223 @Test 224 public void testVisibilityReplication() throws Exception { 225 int retry = 0; 226 try (Table table = writeData(TABLE_NAME, 227 "(" + SECRET + "&" + PUBLIC + ")" + "|(" + CONFIDENTIAL + ")&(" + TOPSECRET + ")", 228 "(" + PRIVATE + "|" + CONFIDENTIAL + ")&(" + PUBLIC + "|" + TOPSECRET + ")", 229 "(" + SECRET + "|" + CONFIDENTIAL + ")" + "&" + "!" + TOPSECRET, 230 CellVisibility.quote(UNICODE_VIS_TAG) + "&" + SECRET);) { 231 Scan s = new Scan(); 232 s.setAuthorizations( 233 new Authorizations(SECRET, CONFIDENTIAL, PRIVATE, TOPSECRET, UNICODE_VIS_TAG)); 234 ResultScanner scanner = table.getScanner(s); 235 Result[] next = scanner.next(4); 236 237 assertTrue(next.length == 4); 238 CellScanner cellScanner = next[0].cellScanner(); 239 cellScanner.advance(); 240 Cell current = cellScanner.current(); 241 assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), current.getRowLength(), 242 row1, 0, row1.length)); 243 cellScanner = next[1].cellScanner(); 244 cellScanner.advance(); 245 current = cellScanner.current(); 246 assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), current.getRowLength(), 247 row2, 0, row2.length)); 248 cellScanner = next[2].cellScanner(); 249 cellScanner.advance(); 250 current = cellScanner.current(); 251 assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), current.getRowLength(), 252 row3, 0, row3.length)); 253 cellScanner = next[3].cellScanner(); 254 cellScanner.advance(); 255 current = cellScanner.current(); 256 assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(), current.getRowLength(), 257 row4, 0, row4.length)); 258 try (Table table2 = TEST_UTIL1.getConnection().getTable(TABLE_NAME);) { 259 s = new Scan(); 260 // Ensure both rows are replicated 261 scanner = table2.getScanner(s); 262 next = scanner.next(4); 263 while (next.length == 0 && retry <= 10) { 264 scanner = table2.getScanner(s); 265 next = scanner.next(4); 266 Thread.sleep(2000); 267 retry++; 268 } 269 assertTrue(next.length == 4); 270 verifyGet(row1, expectedVisString[0], expected[0], false, TOPSECRET, CONFIDENTIAL); 271 TestCoprocessorForTagsAtSink.tags.clear(); 272 verifyGet(row2, expectedVisString[1], expected[1], false, CONFIDENTIAL, PUBLIC); 273 TestCoprocessorForTagsAtSink.tags.clear(); 274 verifyGet(row3, expectedVisString[2], expected[2], false, PRIVATE, SECRET); 275 verifyGet(row3, "", expected[3], true, TOPSECRET, SECRET); 276 verifyGet(row4, expectedVisString[3], expected[4], false, UNICODE_VIS_TAG, SECRET); 277 } 278 } 279 } 280 281 protected static void doAssert(byte[] row, String visTag) throws Exception { 282 if (VisibilityReplicationEndPointForTest.lastEntries == null) { 283 return; // first call 284 } 285 Assert.assertEquals(1, VisibilityReplicationEndPointForTest.lastEntries.size()); 286 List<Cell> cells = VisibilityReplicationEndPointForTest.lastEntries.get(0).getEdit().getCells(); 287 Assert.assertEquals(4, cells.size()); 288 boolean tagFound = false; 289 for (Cell cell : cells) { 290 if ( 291 (Bytes.equals(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), row, 0, 292 row.length)) 293 ) { 294 List<Tag> tags = PrivateCellUtil.getTags(cell); 295 for (Tag tag : tags) { 296 if (tag.getType() == TagType.STRING_VIS_TAG_TYPE) { 297 assertEquals(visTag, Tag.getValueAsString(tag)); 298 tagFound = true; 299 break; 300 } 301 } 302 } 303 } 304 assertTrue(tagFound); 305 } 306 307 protected void verifyGet(final byte[] row, final String visString, final int expected, 308 final boolean nullExpected, final String... auths) throws IOException, InterruptedException { 309 PrivilegedExceptionAction<Void> scanAction = new PrivilegedExceptionAction<Void>() { 310 @Override 311 public Void run() throws Exception { 312 try (Connection connection = ConnectionFactory.createConnection(conf1); 313 Table table2 = connection.getTable(TABLE_NAME)) { 314 CellScanner cellScanner; 315 Cell current; 316 Get get = new Get(row); 317 get.setAuthorizations(new Authorizations(auths)); 318 Result result = table2.get(get); 319 cellScanner = result.cellScanner(); 320 boolean advance = cellScanner.advance(); 321 if (nullExpected) { 322 assertTrue(!advance); 323 return null; 324 } 325 current = cellScanner.current(); 326 assertArrayEquals(CellUtil.cloneRow(current), row); 327 for (Tag tag : TestCoprocessorForTagsAtSink.tags) { 328 LOG.info("The tag type is " + tag.getType()); 329 } 330 assertEquals(expected, TestCoprocessorForTagsAtSink.tags.size()); 331 Tag tag = TestCoprocessorForTagsAtSink.tags.get(1); 332 if (tag.getType() != NON_VIS_TAG_TYPE) { 333 assertEquals(TagType.VISIBILITY_EXP_SERIALIZATION_FORMAT_TAG_TYPE, tag.getType()); 334 } 335 tag = TestCoprocessorForTagsAtSink.tags.get(0); 336 boolean foundNonVisTag = false; 337 for (Tag t : TestCoprocessorForTagsAtSink.tags) { 338 if (t.getType() == NON_VIS_TAG_TYPE) { 339 assertEquals(TEMP, Tag.getValueAsString(t)); 340 foundNonVisTag = true; 341 break; 342 } 343 } 344 doAssert(row, visString); 345 assertTrue(foundNonVisTag); 346 return null; 347 } 348 } 349 }; 350 USER1.runAs(scanAction); 351 } 352 353 public static void addLabels() throws Exception { 354 PrivilegedExceptionAction<VisibilityLabelsResponse> action = 355 new PrivilegedExceptionAction<VisibilityLabelsResponse>() { 356 @Override 357 public VisibilityLabelsResponse run() throws Exception { 358 String[] labels = { SECRET, TOPSECRET, CONFIDENTIAL, PUBLIC, PRIVATE, UNICODE_VIS_TAG }; 359 try (Connection conn = ConnectionFactory.createConnection(conf)) { 360 VisibilityClient.addLabels(conn, labels); 361 } catch (Throwable t) { 362 throw new IOException(t); 363 } 364 return null; 365 } 366 }; 367 SUPERUSER.runAs(action); 368 } 369 370 public static void setAuths(final Configuration conf) throws Exception { 371 PrivilegedExceptionAction<VisibilityLabelsResponse> action = 372 new PrivilegedExceptionAction<VisibilityLabelsResponse>() { 373 @Override 374 public VisibilityLabelsResponse run() throws Exception { 375 try (Connection conn = ConnectionFactory.createConnection(conf)) { 376 return VisibilityClient.setAuths(conn, 377 new String[] { SECRET, CONFIDENTIAL, PRIVATE, TOPSECRET, UNICODE_VIS_TAG }, "user1"); 378 } catch (Throwable e) { 379 throw new Exception(e); 380 } 381 } 382 }; 383 VisibilityLabelsResponse response = SUPERUSER.runAs(action); 384 } 385 386 static Table writeData(TableName tableName, String... labelExps) throws Exception { 387 Table table = TEST_UTIL.getConnection().getTable(TABLE_NAME); 388 int i = 1; 389 List<Put> puts = new ArrayList<>(labelExps.length); 390 for (String labelExp : labelExps) { 391 Put put = new Put(Bytes.toBytes("row" + i)); 392 put.addColumn(fam, qual, HConstants.LATEST_TIMESTAMP, value); 393 put.setCellVisibility(new CellVisibility(labelExp)); 394 put.setAttribute(NON_VISIBILITY, Bytes.toBytes(TEMP)); 395 puts.add(put); 396 i++; 397 } 398 table.put(puts); 399 return table; 400 } 401 402 // A simple BaseRegionbserver impl that allows to add a non-visibility tag from the 403 // attributes of the Put mutation. The existing cells in the put mutation is overwritten 404 // with a new cell that has the visibility tags and the non visibility tag 405 public static class SimpleCP implements RegionCoprocessor, RegionObserver { 406 @Override 407 public Optional<RegionObserver> getRegionObserver() { 408 return Optional.of(this); 409 } 410 411 @Override 412 public void prePut(ObserverContext<RegionCoprocessorEnvironment> e, Put m, WALEdit edit, 413 Durability durability) throws IOException { 414 byte[] attribute = m.getAttribute(NON_VISIBILITY); 415 byte[] cf = null; 416 List<Cell> updatedCells = new ArrayList<>(); 417 if (attribute != null) { 418 for (List<? extends Cell> edits : m.getFamilyCellMap().values()) { 419 for (Cell cell : edits) { 420 KeyValue kv = KeyValueUtil.ensureKeyValue(cell); 421 if (cf == null) { 422 cf = CellUtil.cloneFamily(kv); 423 } 424 Tag tag = new ArrayBackedTag((byte) NON_VIS_TAG_TYPE, attribute); 425 List<Tag> tagList = new ArrayList<>(PrivateCellUtil.getTags(cell).size() + 1); 426 tagList.add(tag); 427 tagList.addAll(PrivateCellUtil.getTags(cell)); 428 Cell newcell = PrivateCellUtil.createCell(kv, tagList); 429 ((List<Cell>) updatedCells).add(newcell); 430 } 431 } 432 m.getFamilyCellMap().remove(cf); 433 // Update the family map 434 m.getFamilyCellMap().put(cf, updatedCells); 435 } 436 } 437 } 438 439 public static class TestCoprocessorForTagsAtSink implements RegionCoprocessor, RegionObserver { 440 public static List<Tag> tags = null; 441 442 @Override 443 public Optional<RegionObserver> getRegionObserver() { 444 return Optional.of(this); 445 } 446 447 @Override 448 public void postGetOp(ObserverContext<RegionCoprocessorEnvironment> e, Get get, 449 List<Cell> results) throws IOException { 450 if (results.size() > 0) { 451 // Check tag presence in the 1st cell in 1st Result 452 if (!results.isEmpty()) { 453 Cell cell = results.get(0); 454 tags = PrivateCellUtil.getTags(cell); 455 } 456 } 457 } 458 } 459 460 /** 461 * An extn of VisibilityReplicationEndpoint to verify the tags that are replicated 462 */ 463 public static class VisibilityReplicationEndPointForTest extends VisibilityReplicationEndpoint { 464 static AtomicInteger replicateCount = new AtomicInteger(); 465 static volatile List<Entry> lastEntries = null; 466 467 public VisibilityReplicationEndPointForTest(ReplicationEndpoint endpoint, 468 VisibilityLabelService visibilityLabelsService) { 469 super(endpoint, visibilityLabelsService); 470 } 471 472 @Override 473 public boolean replicate(ReplicateContext replicateContext) { 474 boolean ret = super.replicate(replicateContext); 475 lastEntries = replicateContext.getEntries(); 476 replicateCount.incrementAndGet(); 477 return ret; 478 } 479 } 480}