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   */package org.apache.hadoop.hbase.rest;
18  
19  import static org.junit.Assert.assertEquals;
20  import static org.junit.Assert.assertNotNull;
21  
22  import java.io.ByteArrayInputStream;
23  import java.io.IOException;
24  import java.io.StringWriter;
25  import java.security.PrivilegedExceptionAction;
26  import java.util.ArrayList;
27  import java.util.Iterator;
28  import java.util.List;
29  import java.util.Random;
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.testclassification.MediumTests;
42  import org.apache.hadoop.hbase.TableName;
43  import org.apache.hadoop.hbase.client.Admin;
44  import org.apache.hadoop.hbase.client.Connection;
45  import org.apache.hadoop.hbase.client.ConnectionFactory;
46  import org.apache.hadoop.hbase.client.Durability;
47  import org.apache.hadoop.hbase.client.HTable;
48  import org.apache.hadoop.hbase.client.Put;
49  import org.apache.hadoop.hbase.client.Table;
50  import org.apache.hadoop.hbase.protobuf.generated.VisibilityLabelsProtos.VisibilityLabelsResponse;
51  import org.apache.hadoop.hbase.rest.client.Client;
52  import org.apache.hadoop.hbase.rest.client.Cluster;
53  import org.apache.hadoop.hbase.rest.client.Response;
54  import org.apache.hadoop.hbase.rest.model.CellModel;
55  import org.apache.hadoop.hbase.rest.model.CellSetModel;
56  import org.apache.hadoop.hbase.rest.model.RowModel;
57  import org.apache.hadoop.hbase.rest.model.ScannerModel;
58  import org.apache.hadoop.hbase.security.User;
59  import org.apache.hadoop.hbase.security.visibility.CellVisibility;
60  import org.apache.hadoop.hbase.security.visibility.ScanLabelGenerator;
61  import org.apache.hadoop.hbase.security.visibility.SimpleScanLabelGenerator;
62  import org.apache.hadoop.hbase.security.visibility.VisibilityClient;
63  import org.apache.hadoop.hbase.security.visibility.VisibilityConstants;
64  import org.apache.hadoop.hbase.security.visibility.VisibilityController;
65  import org.apache.hadoop.hbase.security.visibility.VisibilityUtils;
66  import org.apache.hadoop.hbase.util.Bytes;
67  import org.junit.AfterClass;
68  import org.junit.BeforeClass;
69  import org.junit.Test;
70  import org.junit.experimental.categories.Category;
71  
72  @Category(MediumTests.class)
73  public class TestScannersWithLabels {
74    private static final TableName TABLE = TableName.valueOf("TestScannersWithLabels");
75    private static final String CFA = "a";
76    private static final String CFB = "b";
77    private static final String COLUMN_1 = CFA + ":1";
78    private static final String COLUMN_2 = CFB + ":2";
79    private final static String TOPSECRET = "topsecret";
80    private final static String PUBLIC = "public";
81    private final static String PRIVATE = "private";
82    private final static String CONFIDENTIAL = "confidential";
83    private final static String SECRET = "secret";
84    private static User SUPERUSER;
85  
86    private static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
87    private static final HBaseRESTTestingUtility REST_TEST_UTIL = new HBaseRESTTestingUtility();
88    private static Client client;
89    private static JAXBContext context;
90    private static Marshaller marshaller;
91    private static Unmarshaller unmarshaller;
92    private static Configuration conf;
93  
94    private static int insertData(TableName tableName, String column, double prob) throws IOException {
95      byte[] k = new byte[3];
96      byte[][] famAndQf = KeyValue.parseColumn(Bytes.toBytes(column));
97  
98      List<Put> puts = new ArrayList<>();
99      for (int i = 0; i < 9; i++) {
100       Put put = new Put(Bytes.toBytes("row" + i));
101       put.setDurability(Durability.SKIP_WAL);
102       put.add(famAndQf[0], famAndQf[1], k);
103       put.setCellVisibility(new CellVisibility("(" + SECRET + "|" + CONFIDENTIAL + ")" + "&" + "!"
104           + TOPSECRET));
105       puts.add(put);
106     }
107     try (Table table = new HTable(TEST_UTIL.getConfiguration(), tableName)) {
108       table.put(puts);
109     }
110     return puts.size();
111   }
112 
113   private static int countCellSet(CellSetModel model) {
114     int count = 0;
115     Iterator<RowModel> rows = model.getRows().iterator();
116     while (rows.hasNext()) {
117       RowModel row = rows.next();
118       Iterator<CellModel> cells = row.getCells().iterator();
119       while (cells.hasNext()) {
120         cells.next();
121         count++;
122       }
123     }
124     return count;
125   }
126 
127   @BeforeClass
128   public static void setUpBeforeClass() throws Exception {
129     SUPERUSER = User.createUserForTesting(conf, "admin",
130         new String[] { "supergroup" });
131     conf = TEST_UTIL.getConfiguration();
132     conf.setClass(VisibilityUtils.VISIBILITY_LABEL_GENERATOR_CLASS,
133         SimpleScanLabelGenerator.class, ScanLabelGenerator.class);
134     conf.setInt("hfile.format.version", 3);
135     conf.set("hbase.superuser", SUPERUSER.getShortName());
136     conf.set("hbase.coprocessor.master.classes", VisibilityController.class.getName());
137     conf.set("hbase.coprocessor.region.classes", VisibilityController.class.getName());
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       public VisibilityLabelsResponse run() throws Exception {
170         String[] labels = { SECRET, CONFIDENTIAL, PRIVATE, PUBLIC, TOPSECRET };
171         try (Connection conn = ConnectionFactory.createConnection(conf)) {
172           VisibilityClient.addLabels(conn, labels);
173         } catch (Throwable t) {
174           throw new IOException(t);
175         }
176         return null;
177       }
178     };
179     SUPERUSER.runAs(action);
180   }
181   private static void setAuths() throws Exception {
182     String[] labels = { SECRET, CONFIDENTIAL, PRIVATE, PUBLIC, TOPSECRET };
183     try (Connection conn = ConnectionFactory.createConnection(conf)) {
184       VisibilityClient.setAuths(conn, labels, User.getCurrent().getShortName());
185     } catch (Throwable t) {
186       throw new IOException(t);
187     }
188   }
189   @Test
190   public void testSimpleScannerXMLWithLabelsThatReceivesNoData() throws IOException, JAXBException {
191     final int BATCH_SIZE = 5;
192     // new scanner
193     ScannerModel model = new ScannerModel();
194     model.setBatch(BATCH_SIZE);
195     model.addColumn(Bytes.toBytes(COLUMN_1));
196     model.addLabel(PUBLIC);
197     StringWriter writer = new StringWriter();
198     marshaller.marshal(model, writer);
199     byte[] body = Bytes.toBytes(writer.toString());
200     // recall previous put operation with read-only off
201     conf.set("hbase.rest.readonly", "false");
202     Response response = client.put("/" + TABLE + "/scanner", Constants.MIMETYPE_XML, body);
203     assertEquals(response.getCode(), 201);
204     String scannerURI = response.getLocation();
205     assertNotNull(scannerURI);
206 
207     // get a cell set
208     response = client.get(scannerURI, Constants.MIMETYPE_XML);
209     // Respond with 204 as there are no cells to be retrieved
210     assertEquals(response.getCode(), 204);
211     assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
212   }
213 
214   @Test
215   public void testSimpleScannerXMLWithLabelsThatReceivesData() throws IOException, JAXBException {
216     // new scanner
217     ScannerModel model = new ScannerModel();
218     model.setBatch(5);
219     model.addColumn(Bytes.toBytes(COLUMN_1));
220     model.addLabel(SECRET);
221     StringWriter writer = new StringWriter();
222     marshaller.marshal(model, writer);
223     byte[] body = Bytes.toBytes(writer.toString());
224 
225     // recall previous put operation with read-only off
226     conf.set("hbase.rest.readonly", "false");
227     Response response = client.put("/" + TABLE + "/scanner", Constants.MIMETYPE_XML, body);
228     assertEquals(response.getCode(), 201);
229     String scannerURI = response.getLocation();
230     assertNotNull(scannerURI);
231 
232     // get a cell set
233     response = client.get(scannerURI, Constants.MIMETYPE_XML);
234     // Respond with 204 as there are no cells to be retrieved
235     assertEquals(response.getCode(), 200);
236     assertEquals(Constants.MIMETYPE_XML, response.getHeader("content-type"));
237     CellSetModel cellSet = (CellSetModel) unmarshaller.unmarshal(new ByteArrayInputStream(response
238         .getBody()));
239     assertEquals(countCellSet(cellSet), 5);
240   }
241 
242 }