View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *     http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  package org.apache.hadoop.hbase.rest;
19  
20  import static org.junit.Assert.assertEquals;
21  import static org.junit.Assert.assertNotNull;
22  
23  import java.io.ByteArrayInputStream;
24  import java.io.IOException;
25  import java.io.StringWriter;
26  import java.security.PrivilegedExceptionAction;
27  import java.util.ArrayList;
28  import java.util.Iterator;
29  import java.util.List;
30  
31  import javax.xml.bind.JAXBContext;
32  import javax.xml.bind.JAXBException;
33  import javax.xml.bind.Marshaller;
34  import javax.xml.bind.Unmarshaller;
35  
36  import org.apache.hadoop.conf.Configuration;
37  import org.apache.hadoop.hbase.HBaseTestingUtility;
38  import org.apache.hadoop.hbase.HColumnDescriptor;
39  import org.apache.hadoop.hbase.HTableDescriptor;
40  import org.apache.hadoop.hbase.KeyValue;
41  import org.apache.hadoop.hbase.security.visibility.VisibilityTestUtil;
42  import org.apache.hadoop.hbase.testclassification.MediumTests;
43  import org.apache.hadoop.hbase.TableName;
44  import org.apache.hadoop.hbase.client.Admin;
45  import org.apache.hadoop.hbase.client.Connection;
46  import org.apache.hadoop.hbase.client.ConnectionFactory;
47  import org.apache.hadoop.hbase.client.Durability;
48  import org.apache.hadoop.hbase.client.HTable;
49  import org.apache.hadoop.hbase.client.Put;
50  import org.apache.hadoop.hbase.client.Table;
51  import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.VisibilityLabelsResponse;
52  import org.apache.hadoop.hbase.rest.client.Client;
53  import org.apache.hadoop.hbase.rest.client.Cluster;
54  import org.apache.hadoop.hbase.rest.client.Response;
55  import org.apache.hadoop.hbase.rest.model.CellModel;
56  import org.apache.hadoop.hbase.rest.model.CellSetModel;
57  import org.apache.hadoop.hbase.rest.model.RowModel;
58  import org.apache.hadoop.hbase.rest.model.ScannerModel;
59  import org.apache.hadoop.hbase.security.User;
60  import org.apache.hadoop.hbase.security.visibility.CellVisibility;
61  import org.apache.hadoop.hbase.security.visibility.ScanLabelGenerator;
62  import org.apache.hadoop.hbase.security.visibility.SimpleScanLabelGenerator;
63  import org.apache.hadoop.hbase.security.visibility.VisibilityClient;
64  import org.apache.hadoop.hbase.security.visibility.VisibilityConstants;
65  import org.apache.hadoop.hbase.security.visibility.VisibilityController;
66  import org.apache.hadoop.hbase.security.visibility.VisibilityUtils;
67  import org.apache.hadoop.hbase.util.Bytes;
68  import org.junit.AfterClass;
69  import org.junit.BeforeClass;
70  import org.junit.Test;
71  import org.junit.experimental.categories.Category;
72  
73  @Category(MediumTests.class)
74  public class TestScannersWithLabels {
75    private static final TableName TABLE = TableName.valueOf("TestScannersWithLabels");
76    private static final String CFA = "a";
77    private static final String CFB = "b";
78    private static final String COLUMN_1 = CFA + ":1";
79    private static final String COLUMN_2 = CFB + ":2";
80    private final static String TOPSECRET = "topsecret";
81    private final static String PUBLIC = "public";
82    private final static String PRIVATE = "private";
83    private final static String CONFIDENTIAL = "confidential";
84    private final static String SECRET = "secret";
85    private static User SUPERUSER;
86  
87    private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
88    private static final HBaseRESTTestingUtility REST_TEST_UTIL = new HBaseRESTTestingUtility();
89    private static Client client;
90    private static JAXBContext context;
91    private static Marshaller marshaller;
92    private static Unmarshaller unmarshaller;
93    private static Configuration conf;
94  
95    private static int insertData(TableName tableName, String column, double prob)
96        throws IOException {
97      byte[] k = new byte[3];
98      byte[][] famAndQf = KeyValue.parseColumn(Bytes.toBytes(column));
99  
100     List<Put> puts = new ArrayList<>();
101     for (int i = 0; i < 9; i++) {
102       Put put = new Put(Bytes.toBytes("row" + i));
103       put.setDurability(Durability.SKIP_WAL);
104       put.add(famAndQf[0], famAndQf[1], k);
105       put.setCellVisibility(new CellVisibility("(" + SECRET + "|" + CONFIDENTIAL + ")" + "&" + "!"
106           + TOPSECRET));
107       puts.add(put);
108     }
109     try (Table table = new HTable(TEST_UTIL.getConfiguration(), tableName)) {
110       table.put(puts);
111     }
112     return puts.size();
113   }
114 
115   private static int countCellSet(CellSetModel model) {
116     int count = 0;
117     Iterator<RowModel> rows = model.getRows().iterator();
118     while (rows.hasNext()) {
119       RowModel row = rows.next();
120       Iterator<CellModel> cells = row.getCells().iterator();
121       while (cells.hasNext()) {
122         cells.next();
123         count++;
124       }
125     }
126     return count;
127   }
128 
129   @BeforeClass
130   public static void setUpBeforeClass() throws Exception {
131     SUPERUSER = User.createUserForTesting(conf, "admin",
132         new String[] { "supergroup" });
133     conf = TEST_UTIL.getConfiguration();
134     conf.setClass(VisibilityUtils.VISIBILITY_LABEL_GENERATOR_CLASS,
135         SimpleScanLabelGenerator.class, ScanLabelGenerator.class);
136     conf.set("hbase.superuser", SUPERUSER.getShortName());
137     VisibilityTestUtil.enableVisiblityLabels(conf);
138     TEST_UTIL.startMiniCluster(1);
139     // Wait for the labels table to become available
140     TEST_UTIL.waitTableEnabled(VisibilityConstants.LABELS_TABLE_NAME.getName(), 50000);
141     createLabels();
142     setAuths();
143     REST_TEST_UTIL.startServletContainer(conf);
144     client = new Client(new Cluster().add("localhost", REST_TEST_UTIL.getServletPort()));
145     context = JAXBContext.newInstance(CellModel.class, CellSetModel.class, RowModel.class,
146         ScannerModel.class);
147     marshaller = context.createMarshaller();
148     unmarshaller = context.createUnmarshaller();
149     Admin admin = TEST_UTIL.getHBaseAdmin();
150     if (admin.tableExists(TABLE)) {
151       return;
152     }
153     HTableDescriptor htd = new HTableDescriptor(TABLE);
154     htd.addFamily(new HColumnDescriptor(CFA));
155     htd.addFamily(new HColumnDescriptor(CFB));
156     admin.createTable(htd);
157     insertData(TABLE, COLUMN_1, 1.0);
158     insertData(TABLE, COLUMN_2, 0.5);
159   }
160 
161   @AfterClass
162   public static void tearDownAfterClass() throws Exception {
163     REST_TEST_UTIL.shutdownServletContainer();
164     TEST_UTIL.shutdownMiniCluster();
165   }
166 
167   private static void createLabels() throws IOException, InterruptedException {
168     PrivilegedExceptionAction<VisibilityLabelsResponse> action = new PrivilegedExceptionAction<VisibilityLabelsResponse>() {
169       @Override
170       public VisibilityLabelsResponse run() throws Exception {
171         String[] labels = { SECRET, CONFIDENTIAL, PRIVATE, PUBLIC, TOPSECRET };
172         try (Connection conn = ConnectionFactory.createConnection(conf)) {
173           VisibilityClient.addLabels(conn, labels);
174         } catch (Throwable t) {
175           throw new IOException(t);
176         }
177         return null;
178       }
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     assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
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 }