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 = COPYRIGHT + "\"" + ACCENT + "\\" + SECRET + "\""
107      + "\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\")",
126      "(\"secret\"&\"" + COPYRIGHT + "\\\"" + ACCENT + "\\\\" + SECRET + "\\\"" + "\u0027&\\\\"
127          + "\")" };
128
129  @Rule
130  public final TestName TEST_NAME = new TestName();
131  public static User SUPERUSER, USER1;
132
133  @Before
134  public void setup() throws Exception {
135    // setup configuration
136    conf = HBaseConfiguration.create();
137    conf.setInt("hfile.format.version", 3);
138    conf.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/1");
139    conf.setInt("replication.source.size.capacity", 10240);
140    conf.setLong("replication.source.sleepforretries", 100);
141    conf.setInt("hbase.regionserver.maxlogs", 10);
142    conf.setLong("hbase.master.logcleaner.ttl", 10);
143    conf.setInt("zookeeper.recovery.retry", 1);
144    conf.setInt("zookeeper.recovery.retry.intervalmill", 10);
145    conf.setLong(HConstants.THREAD_WAKE_FREQUENCY, 100);
146    conf.setInt("replication.stats.thread.period.seconds", 5);
147    conf.setBoolean("hbase.tests.use.shortcircuit.reads", false);
148    setVisibilityLabelServiceImpl(conf);
149    conf.setStrings(HConstants.REPLICATION_CODEC_CONF_KEY, KeyValueCodecWithTags.class.getName());
150    VisibilityTestUtil.enableVisiblityLabels(conf);
151    conf.set(CoprocessorHost.REGIONSERVER_COPROCESSOR_CONF_KEY,
152        VisibilityReplication.class.getName());
153    conf.setStrings(CoprocessorHost.USER_REGION_COPROCESSOR_CONF_KEY,
154        SimpleCP.class.getName());
155    // Have to reset conf1 in case zk cluster location different
156    // than default
157    conf.setClass(VisibilityUtils.VISIBILITY_LABEL_GENERATOR_CLASS, SimpleScanLabelGenerator.class,
158        ScanLabelGenerator.class);
159    conf.set("hbase.superuser", User.getCurrent().getShortName());
160    SUPERUSER = User.createUserForTesting(conf, User.getCurrent().getShortName(),
161        new String[] { "supergroup" });
162    // User.createUserForTesting(conf, User.getCurrent().getShortName(), new
163    // String[] { "supergroup" });
164    USER1 = User.createUserForTesting(conf, "user1", new String[] {});
165    TEST_UTIL = new HBaseTestingUtility(conf);
166    TEST_UTIL.startMiniZKCluster();
167    MiniZooKeeperCluster miniZK = TEST_UTIL.getZkCluster();
168    zkw1 = new ZKWatcher(conf, "cluster1", null, true);
169
170    // Base conf2 on conf1 so it gets the right zk cluster.
171    conf1 = HBaseConfiguration.create(conf);
172    conf1.setInt("hfile.format.version", 3);
173    conf1.set(HConstants.ZOOKEEPER_ZNODE_PARENT, "/2");
174    conf1.setInt(HConstants.HBASE_CLIENT_RETRIES_NUMBER, 6);
175    conf1.setBoolean("hbase.tests.use.shortcircuit.reads", false);
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 ZKWatcher(conf1, "cluster2", null, true);
184
185    TEST_UTIL.startMiniCluster(1);
186    admin = TEST_UTIL.getAdmin();
187    // Wait for the labels table to become available
188    TEST_UTIL.waitTableEnabled(LABELS_TABLE_NAME.getName(), 50000);
189    TEST_UTIL1.startMiniCluster(1);
190
191    ReplicationPeerConfig rpc = new ReplicationPeerConfig();
192    rpc.setClusterKey(TEST_UTIL1.getClusterKey());
193    admin.addReplicationPeer("2", rpc);
194
195    Admin hBaseAdmin = TEST_UTIL.getAdmin();
196    HTableDescriptor table = new HTableDescriptor(TABLE_NAME);
197    HColumnDescriptor desc = new HColumnDescriptor(fam);
198    desc.setScope(HConstants.REPLICATION_SCOPE_GLOBAL);
199    table.addFamily(desc);
200    try {
201      hBaseAdmin.createTable(table);
202    } finally {
203      if (hBaseAdmin != null) {
204        hBaseAdmin.close();
205      }
206    }
207    Admin hBaseAdmin1 = TEST_UTIL1.getAdmin();
208    try {
209      hBaseAdmin1.createTable(table);
210    } finally {
211      if (hBaseAdmin1 != null) {
212        hBaseAdmin1.close();
213      }
214    }
215    addLabels();
216    setAuths(conf);
217    setAuths(conf1);
218  }
219
220  protected static void setVisibilityLabelServiceImpl(Configuration conf) {
221    conf.setClass(VisibilityLabelServiceManager.VISIBILITY_LABEL_SERVICE_CLASS,
222        DefaultVisibilityLabelServiceImpl.class, VisibilityLabelService.class);
223  }
224
225  @Test
226  public void testVisibilityReplication() throws Exception {
227    int retry = 0;
228    try (Table table = writeData(TABLE_NAME, "(" + SECRET + "&" + PUBLIC + ")" + "|(" + CONFIDENTIAL
229            + ")&(" + TOPSECRET + ")", "(" + PRIVATE + "|" + CONFIDENTIAL + ")&(" + PUBLIC + "|"
230            + TOPSECRET + ")", "(" + SECRET + "|" + CONFIDENTIAL + ")" + "&" + "!" + TOPSECRET,
231        CellVisibility.quote(UNICODE_VIS_TAG) + "&" + SECRET);) {
232      Scan s = new Scan();
233      s.setAuthorizations(new Authorizations(SECRET, CONFIDENTIAL, PRIVATE, TOPSECRET,
234          UNICODE_VIS_TAG));
235      ResultScanner scanner = table.getScanner(s);
236      Result[] next = scanner.next(4);
237
238      assertTrue(next.length == 4);
239      CellScanner cellScanner = next[0].cellScanner();
240      cellScanner.advance();
241      Cell current = cellScanner.current();
242      assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(),
243          current.getRowLength(), row1, 0, row1.length));
244      cellScanner = next[1].cellScanner();
245      cellScanner.advance();
246      current = cellScanner.current();
247      assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(),
248          current.getRowLength(), row2, 0, row2.length));
249      cellScanner = next[2].cellScanner();
250      cellScanner.advance();
251      current = cellScanner.current();
252      assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(),
253          current.getRowLength(), row3, 0, row3.length));
254      cellScanner = next[3].cellScanner();
255      cellScanner.advance();
256      current = cellScanner.current();
257      assertTrue(Bytes.equals(current.getRowArray(), current.getRowOffset(),
258          current.getRowLength(), row4, 0, row4.length));
259      try (Table table2 = TEST_UTIL1.getConnection().getTable(TABLE_NAME);) {
260        s = new Scan();
261        // Ensure both rows are replicated
262        scanner = table2.getScanner(s);
263        next = scanner.next(4);
264        while (next.length == 0 && retry <= 10) {
265          scanner = table2.getScanner(s);
266          next = scanner.next(4);
267          Thread.sleep(2000);
268          retry++;
269        }
270        assertTrue(next.length == 4);
271        verifyGet(row1, expectedVisString[0], expected[0], false, TOPSECRET, CONFIDENTIAL);
272        TestCoprocessorForTagsAtSink.tags.clear();
273        verifyGet(row2, expectedVisString[1], expected[1], false, CONFIDENTIAL, PUBLIC);
274        TestCoprocessorForTagsAtSink.tags.clear();
275        verifyGet(row3, expectedVisString[2], expected[2], false, PRIVATE, SECRET);
276        verifyGet(row3, "", expected[3], true, TOPSECRET, SECRET);
277        verifyGet(row4, expectedVisString[3], expected[4], false, UNICODE_VIS_TAG, SECRET);
278      }
279    }
280  }
281
282  protected static void doAssert(byte[] row, String visTag) throws Exception {
283    if (VisibilityReplicationEndPointForTest.lastEntries == null) {
284      return; // first call
285    }
286    Assert.assertEquals(1, VisibilityReplicationEndPointForTest.lastEntries.size());
287    List<Cell> cells = VisibilityReplicationEndPointForTest.lastEntries.get(0).getEdit().getCells();
288    Assert.assertEquals(4, cells.size());
289    boolean tagFound = false;
290    for (Cell cell : cells) {
291      if ((Bytes.equals(cell.getRowArray(), cell.getRowOffset(), cell.getRowLength(), row, 0,
292          row.length))) {
293        List<Tag> tags = PrivateCellUtil.getTags(cell);
294        for (Tag tag : tags) {
295          if (tag.getType() == TagType.STRING_VIS_TAG_TYPE) {
296            assertEquals(visTag, Tag.getValueAsString(tag));
297            tagFound = true;
298            break;
299          }
300        }
301      }
302    }
303    assertTrue(tagFound);
304  }
305
306  protected void verifyGet(final byte[] row, final String visString, final int expected,
307      final boolean nullExpected, final String... auths) throws IOException,
308      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, new String[] { SECRET,
377            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  // A simple BaseRegionbserver impl that allows to add a non-visibility tag from the
402  // attributes of the Put mutation.  The existing cells in the put mutation is overwritten
403  // with a new cell that has the visibility tags and the non visibility tag
404  public static class SimpleCP implements RegionCoprocessor, RegionObserver {
405    @Override
406    public Optional<RegionObserver> getRegionObserver() {
407      return Optional.of(this);
408    }
409
410    @Override
411    public void prePut(ObserverContext<RegionCoprocessorEnvironment> e, Put m, WALEdit edit,
412        Durability durability) throws IOException {
413      byte[] attribute = m.getAttribute(NON_VISIBILITY);
414      byte[] cf = null;
415      List<Cell> updatedCells = new ArrayList<>();
416      if (attribute != null) {
417        for (List<? extends Cell> edits : m.getFamilyCellMap().values()) {
418          for (Cell cell : edits) {
419            KeyValue kv = KeyValueUtil.ensureKeyValue(cell);
420            if (cf == null) {
421              cf = CellUtil.cloneFamily(kv);
422            }
423            Tag tag = new ArrayBackedTag((byte) NON_VIS_TAG_TYPE, attribute);
424            List<Tag> tagList = new ArrayList<>(PrivateCellUtil.getTags(cell).size() + 1);
425            tagList.add(tag);
426            tagList.addAll(PrivateCellUtil.getTags(cell));
427            Cell newcell = PrivateCellUtil.createCell(kv, tagList);
428            ((List<Cell>) updatedCells).add(newcell);
429          }
430        }
431        m.getFamilyCellMap().remove(cf);
432        // Update the family map
433        m.getFamilyCellMap().put(cf, updatedCells);
434      }
435    }
436  }
437
438  public static class TestCoprocessorForTagsAtSink implements RegionCoprocessor, RegionObserver {
439    public static List<Tag> tags = null;
440
441    @Override
442    public Optional<RegionObserver> getRegionObserver() {
443      return Optional.of(this);
444    }
445
446    @Override
447    public void postGetOp(ObserverContext<RegionCoprocessorEnvironment> e, Get get,
448        List<Cell> results) throws IOException {
449      if (results.size() > 0) {
450        // Check tag presence in the 1st cell in 1st Result
451        if (!results.isEmpty()) {
452          Cell cell = results.get(0);
453          tags = PrivateCellUtil.getTags(cell);
454        }
455      }
456    }
457  }
458
459  /**
460   * An extn of VisibilityReplicationEndpoint to verify the tags that are replicated
461   */
462  public static class VisibilityReplicationEndPointForTest extends VisibilityReplicationEndpoint {
463    static AtomicInteger replicateCount = new AtomicInteger();
464    static volatile List<Entry> lastEntries = null;
465
466    public VisibilityReplicationEndPointForTest(ReplicationEndpoint endpoint,
467        VisibilityLabelService visibilityLabelsService) {
468      super(endpoint, visibilityLabelsService);
469    }
470
471    @Override
472    public boolean replicate(ReplicateContext replicateContext) {
473      boolean ret = super.replicate(replicateContext);
474      lastEntries = replicateContext.getEntries();
475      replicateCount.incrementAndGet();
476      return ret;
477    }
478  }
479}