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.rest;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertNotNull;
022
023import java.io.ByteArrayInputStream;
024import java.io.IOException;
025import java.io.StringWriter;
026import java.security.PrivilegedExceptionAction;
027import java.util.ArrayList;
028import java.util.Iterator;
029import java.util.List;
030import javax.xml.bind.JAXBContext;
031import javax.xml.bind.JAXBException;
032import javax.xml.bind.Marshaller;
033import javax.xml.bind.Unmarshaller;
034import org.apache.hadoop.conf.Configuration;
035import org.apache.hadoop.hbase.CellUtil;
036import org.apache.hadoop.hbase.HBaseClassTestRule;
037import org.apache.hadoop.hbase.HBaseTestingUtility;
038import org.apache.hadoop.hbase.HColumnDescriptor;
039import org.apache.hadoop.hbase.HTableDescriptor;
040import org.apache.hadoop.hbase.TableName;
041import org.apache.hadoop.hbase.client.Admin;
042import org.apache.hadoop.hbase.client.Connection;
043import org.apache.hadoop.hbase.client.ConnectionFactory;
044import org.apache.hadoop.hbase.client.Durability;
045import org.apache.hadoop.hbase.client.Put;
046import org.apache.hadoop.hbase.client.Table;
047import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.VisibilityLabelsResponse;
048import org.apache.hadoop.hbase.rest.client.Client;
049import org.apache.hadoop.hbase.rest.client.Cluster;
050import org.apache.hadoop.hbase.rest.client.Response;
051import org.apache.hadoop.hbase.rest.model.CellModel;
052import org.apache.hadoop.hbase.rest.model.CellSetModel;
053import org.apache.hadoop.hbase.rest.model.RowModel;
054import org.apache.hadoop.hbase.rest.model.ScannerModel;
055import org.apache.hadoop.hbase.security.User;
056import org.apache.hadoop.hbase.security.visibility.CellVisibility;
057import org.apache.hadoop.hbase.security.visibility.ScanLabelGenerator;
058import org.apache.hadoop.hbase.security.visibility.SimpleScanLabelGenerator;
059import org.apache.hadoop.hbase.security.visibility.VisibilityClient;
060import org.apache.hadoop.hbase.security.visibility.VisibilityConstants;
061import org.apache.hadoop.hbase.security.visibility.VisibilityTestUtil;
062import org.apache.hadoop.hbase.security.visibility.VisibilityUtils;
063import org.apache.hadoop.hbase.testclassification.MediumTests;
064import org.apache.hadoop.hbase.testclassification.RestTests;
065import org.apache.hadoop.hbase.util.Bytes;
066import org.junit.AfterClass;
067import org.junit.BeforeClass;
068import org.junit.ClassRule;
069import org.junit.Test;
070import org.junit.experimental.categories.Category;
071
072@Category({RestTests.class, MediumTests.class})
073public class TestScannersWithLabels {
074  @ClassRule
075  public static final HBaseClassTestRule CLASS_RULE =
076      HBaseClassTestRule.forClass(TestScannersWithLabels.class);
077
078  private static final TableName TABLE = TableName.valueOf("TestScannersWithLabels");
079  private static final String CFA = "a";
080  private static final String CFB = "b";
081  private static final String COLUMN_1 = CFA + ":1";
082  private static final String COLUMN_2 = CFB + ":2";
083  private final static String TOPSECRET = "topsecret";
084  private final static String PUBLIC = "public";
085  private final static String PRIVATE = "private";
086  private final static String CONFIDENTIAL = "confidential";
087  private final static String SECRET = "secret";
088  private static User SUPERUSER;
089
090  private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
091  private static final HBaseRESTTestingUtility REST_TEST_UTIL = new HBaseRESTTestingUtility();
092  private static Client client;
093  private static JAXBContext context;
094  private static Marshaller marshaller;
095  private static Unmarshaller unmarshaller;
096  private static Configuration conf;
097
098  private static int insertData(TableName tableName, String column, double prob)
099      throws IOException {
100    byte[] k = new byte[3];
101    byte[][] famAndQf = CellUtil.parseColumn(Bytes.toBytes(column));
102
103    List<Put> puts = new ArrayList<>(9);
104    for (int i = 0; i < 9; i++) {
105      Put put = new Put(Bytes.toBytes("row" + i));
106      put.setDurability(Durability.SKIP_WAL);
107      put.addColumn(famAndQf[0], famAndQf[1], k);
108      put.setCellVisibility(new CellVisibility("(" + SECRET + "|" + CONFIDENTIAL + ")" + "&" + "!"
109          + TOPSECRET));
110      puts.add(put);
111    }
112    try (Table table = TEST_UTIL.getConnection().getTable(tableName)) {
113      table.put(puts);
114    }
115    return puts.size();
116  }
117
118  private static int countCellSet(CellSetModel model) {
119    int count = 0;
120    Iterator<RowModel> rows = model.getRows().iterator();
121    while (rows.hasNext()) {
122      RowModel row = rows.next();
123      Iterator<CellModel> cells = row.getCells().iterator();
124      while (cells.hasNext()) {
125        cells.next();
126        count++;
127      }
128    }
129    return count;
130  }
131
132  @BeforeClass
133  public static void setUpBeforeClass() throws Exception {
134    SUPERUSER = User.createUserForTesting(conf, "admin",
135        new String[] { "supergroup" });
136    conf = TEST_UTIL.getConfiguration();
137    conf.setClass(VisibilityUtils.VISIBILITY_LABEL_GENERATOR_CLASS,
138        SimpleScanLabelGenerator.class, ScanLabelGenerator.class);
139    conf.set("hbase.superuser", SUPERUSER.getShortName());
140    VisibilityTestUtil.enableVisiblityLabels(conf);
141    TEST_UTIL.startMiniCluster(1);
142    // Wait for the labels table to become available
143    TEST_UTIL.waitTableEnabled(VisibilityConstants.LABELS_TABLE_NAME.getName(), 50000);
144    createLabels();
145    setAuths();
146    REST_TEST_UTIL.startServletContainer(conf);
147    client = new Client(new Cluster().add("localhost", REST_TEST_UTIL.getServletPort()));
148    context = JAXBContext.newInstance(CellModel.class, CellSetModel.class, RowModel.class,
149        ScannerModel.class);
150    marshaller = context.createMarshaller();
151    unmarshaller = context.createUnmarshaller();
152    Admin admin = TEST_UTIL.getAdmin();
153    if (admin.tableExists(TABLE)) {
154      return;
155    }
156    HTableDescriptor htd = new HTableDescriptor(TABLE);
157    htd.addFamily(new HColumnDescriptor(CFA));
158    htd.addFamily(new HColumnDescriptor(CFB));
159    admin.createTable(htd);
160    insertData(TABLE, COLUMN_1, 1.0);
161    insertData(TABLE, COLUMN_2, 0.5);
162  }
163
164  @AfterClass
165  public static void tearDownAfterClass() throws Exception {
166    REST_TEST_UTIL.shutdownServletContainer();
167    TEST_UTIL.shutdownMiniCluster();
168  }
169
170  private static void createLabels() throws IOException, InterruptedException {
171    PrivilegedExceptionAction<VisibilityLabelsResponse> action = () -> {
172      String[] labels = { SECRET, CONFIDENTIAL, PRIVATE, PUBLIC, TOPSECRET };
173      try (Connection conn = ConnectionFactory.createConnection(conf)) {
174        VisibilityClient.addLabels(conn, labels);
175      } catch (Throwable t) {
176        throw new IOException(t);
177      }
178      return null;
179    };
180    SUPERUSER.runAs(action);
181  }
182
183  private static void setAuths() throws Exception {
184    String[] labels = { SECRET, CONFIDENTIAL, PRIVATE, PUBLIC, TOPSECRET };
185    try (Connection conn = ConnectionFactory.createConnection(conf)) {
186      VisibilityClient.setAuths(conn, labels, User.getCurrent().getShortName());
187    } catch (Throwable t) {
188      throw new IOException(t);
189    }
190  }
191
192  @Test
193  public void testSimpleScannerXMLWithLabelsThatReceivesNoData() throws IOException, JAXBException {
194    final int BATCH_SIZE = 5;
195    // new scanner
196    ScannerModel model = new ScannerModel();
197    model.setBatch(BATCH_SIZE);
198    model.addColumn(Bytes.toBytes(COLUMN_1));
199    model.addLabel(PUBLIC);
200    StringWriter writer = new StringWriter();
201    marshaller.marshal(model, writer);
202    byte[] body = Bytes.toBytes(writer.toString());
203    // recall previous put operation with read-only off
204    conf.set("hbase.rest.readonly", "false");
205    Response response = client.put("/" + TABLE + "/scanner", Constants.MIMETYPE_XML, body);
206    assertEquals(201, response.getCode());
207    String scannerURI = response.getLocation();
208    assertNotNull(scannerURI);
209
210    // get a cell set
211    response = client.get(scannerURI, Constants.MIMETYPE_XML);
212    // Respond with 204 as there are no cells to be retrieved
213    assertEquals(204, response.getCode());
214    // With no content in the payload, the 'Content-Type' header is not echo back
215  }
216
217  @Test
218  public void testSimpleScannerXMLWithLabelsThatReceivesData() throws IOException, JAXBException {
219    // new scanner
220    ScannerModel model = new ScannerModel();
221    model.setBatch(5);
222    model.addColumn(Bytes.toBytes(COLUMN_1));
223    model.addLabel(SECRET);
224    StringWriter writer = new StringWriter();
225    marshaller.marshal(model, writer);
226    byte[] body = Bytes.toBytes(writer.toString());
227
228    // recall previous put operation with read-only off
229    conf.set("hbase.rest.readonly", "false");
230    Response response = client.put("/" + TABLE + "/scanner", Constants.MIMETYPE_XML, body);
231    assertEquals(201, response.getCode());
232    String scannerURI = response.getLocation();
233    assertNotNull(scannerURI);
234
235    // get a cell set
236    response = client.get(scannerURI, Constants.MIMETYPE_XML);
237    // Respond with 204 as there are no cells to be retrieved
238    assertEquals(200, response.getCode());
239    assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
240    CellSetModel cellSet = (CellSetModel) unmarshaller.unmarshal(new ByteArrayInputStream(response
241        .getBody()));
242    assertEquals(5, countCellSet(cellSet));
243  }
244}