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.wal;
019
020import static org.junit.Assert.assertFalse;
021import static org.junit.Assert.assertTrue;
022
023import java.io.FileNotFoundException;
024import java.io.IOException;
025import java.nio.ByteBuffer;
026import java.util.NavigableMap;
027import java.util.TreeMap;
028import org.apache.commons.io.IOUtils;
029import org.apache.hadoop.conf.Configuration;
030import org.apache.hadoop.fs.FSDataInputStream;
031import org.apache.hadoop.fs.FileStatus;
032import org.apache.hadoop.fs.FileSystem;
033import org.apache.hadoop.fs.Path;
034import org.apache.hadoop.hbase.ByteBufferKeyValue;
035import org.apache.hadoop.hbase.HBaseClassTestRule;
036import org.apache.hadoop.hbase.HBaseTestingUtility;
037import org.apache.hadoop.hbase.HConstants;
038import org.apache.hadoop.hbase.KeyValue;
039import org.apache.hadoop.hbase.ServerName;
040import org.apache.hadoop.hbase.TableName;
041import org.apache.hadoop.hbase.client.RegionInfo;
042import org.apache.hadoop.hbase.client.RegionInfoBuilder;
043import org.apache.hadoop.hbase.io.crypto.KeyProviderForTesting;
044import org.apache.hadoop.hbase.regionserver.MultiVersionConcurrencyControl;
045import org.apache.hadoop.hbase.regionserver.wal.ProtobufLogReader;
046import org.apache.hadoop.hbase.regionserver.wal.ProtobufLogWriter;
047import org.apache.hadoop.hbase.regionserver.wal.SecureAsyncProtobufLogWriter;
048import org.apache.hadoop.hbase.regionserver.wal.SecureProtobufLogReader;
049import org.apache.hadoop.hbase.regionserver.wal.SecureProtobufLogWriter;
050import org.apache.hadoop.hbase.regionserver.wal.SecureWALCellCodec;
051import org.apache.hadoop.hbase.regionserver.wal.WALCellCodec;
052import org.apache.hadoop.hbase.testclassification.RegionServerTests;
053import org.apache.hadoop.hbase.testclassification.SmallTests;
054import org.apache.hadoop.hbase.util.Bytes;
055import org.apache.hadoop.hbase.util.CommonFSUtils;
056import org.apache.hadoop.hbase.zookeeper.ZKSplitLog;
057import org.junit.BeforeClass;
058import org.junit.ClassRule;
059import org.junit.Rule;
060import org.junit.Test;
061import org.junit.experimental.categories.Category;
062import org.junit.rules.TestName;
063
064/**
065 * Test that verifies WAL written by SecureProtobufLogWriter is not readable by ProtobufLogReader
066 */
067@Category({RegionServerTests.class, SmallTests.class})
068public class TestWALReaderOnSecureWAL {
069
070  @ClassRule
071  public static final HBaseClassTestRule CLASS_RULE =
072      HBaseClassTestRule.forClass(TestWALReaderOnSecureWAL.class);
073
074  static final HBaseTestingUtility TEST_UTIL = new HBaseTestingUtility();
075  final byte[] value = Bytes.toBytes("Test value");
076
077  private static final String WAL_ENCRYPTION = "hbase.regionserver.wal.encryption";
078
079  @Rule
080  public TestName currentTest = new TestName();
081
082  @BeforeClass
083  public static void setUpBeforeClass() throws Exception {
084    Configuration conf = TEST_UTIL.getConfiguration();
085    conf.set(HConstants.CRYPTO_KEYPROVIDER_CONF_KEY, KeyProviderForTesting.class.getName());
086    conf.set(HConstants.CRYPTO_MASTERKEY_NAME_CONF_KEY, "hbase");
087    conf.setBoolean("hbase.hlog.split.skip.errors", true);
088    conf.setBoolean(HConstants.ENABLE_WAL_ENCRYPTION, true);
089    CommonFSUtils.setRootDir(conf, TEST_UTIL.getDataTestDir());
090  }
091
092  private Path writeWAL(final WALFactory wals, final String tblName, boolean offheap)
093      throws IOException {
094    Configuration conf = TEST_UTIL.getConfiguration();
095    String clsName = conf.get(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, WALCellCodec.class.getName());
096    conf.setClass(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, SecureWALCellCodec.class,
097      WALCellCodec.class);
098    try {
099      TableName tableName = TableName.valueOf(tblName);
100      NavigableMap<byte[], Integer> scopes = new TreeMap<>(Bytes.BYTES_COMPARATOR);
101      scopes.put(tableName.getName(), 0);
102      RegionInfo regionInfo = RegionInfoBuilder.newBuilder(tableName).build();
103      final int total = 10;
104      final byte[] row = Bytes.toBytes("row");
105      final byte[] family = Bytes.toBytes("family");
106      final MultiVersionConcurrencyControl mvcc = new MultiVersionConcurrencyControl(1);
107
108      // Write the WAL
109      WAL wal = wals.getWAL(regionInfo);
110      for (int i = 0; i < total; i++) {
111        WALEdit kvs = new WALEdit();
112        KeyValue kv = new KeyValue(row, family, Bytes.toBytes(i), value);
113        if (offheap) {
114          ByteBuffer bb = ByteBuffer.allocateDirect(kv.getBuffer().length);
115          bb.put(kv.getBuffer());
116          ByteBufferKeyValue offheapKV = new ByteBufferKeyValue(bb, 0, kv.getLength());
117          kvs.add(offheapKV);
118        } else {
119          kvs.add(kv);
120        }
121        wal.appendData(regionInfo, new WALKeyImpl(regionInfo.getEncodedNameAsBytes(), tableName,
122          System.currentTimeMillis(), mvcc, scopes), kvs);
123      }
124      wal.sync();
125      final Path walPath = AbstractFSWALProvider.getCurrentFileName(wal);
126      wal.shutdown();
127
128      return walPath;
129    } finally {
130      // restore the cell codec class
131      conf.set(WALCellCodec.WAL_CELL_CODEC_CLASS_KEY, clsName);
132    }
133  }
134
135  @Test()
136  public void testWALReaderOnSecureWALWithKeyValues() throws Exception {
137    testSecureWALInternal(false);
138  }
139
140  @Test()
141  public void testWALReaderOnSecureWALWithOffheapKeyValues() throws Exception {
142    testSecureWALInternal(true);
143  }
144
145  private void testSecureWALInternal(boolean offheap) throws IOException, FileNotFoundException {
146    Configuration conf = TEST_UTIL.getConfiguration();
147    conf.setClass("hbase.regionserver.hlog.reader.impl", ProtobufLogReader.class,
148      WAL.Reader.class);
149    conf.setClass("hbase.regionserver.hlog.writer.impl", SecureProtobufLogWriter.class,
150      WALProvider.Writer.class);
151    conf.setClass("hbase.regionserver.hlog.async.writer.impl", SecureAsyncProtobufLogWriter.class,
152      WALProvider.AsyncWriter.class);
153    conf.setBoolean(WAL_ENCRYPTION, true);
154    FileSystem fs = TEST_UTIL.getTestFileSystem();
155    final WALFactory wals = new WALFactory(conf, currentTest.getMethodName());
156    Path walPath = writeWAL(wals, currentTest.getMethodName(), offheap);
157
158    // Insure edits are not plaintext
159    long length = fs.getFileStatus(walPath).getLen();
160    FSDataInputStream in = fs.open(walPath);
161    byte[] fileData = new byte[(int)length];
162    IOUtils.readFully(in, fileData);
163    in.close();
164    assertFalse("Cells appear to be plaintext", Bytes.contains(fileData, value));
165
166    // Confirm the WAL cannot be read back by ProtobufLogReader
167    try {
168      wals.createReader(TEST_UTIL.getTestFileSystem(), walPath);
169      assertFalse(true);
170    } catch (IOException ioe) {
171      // expected IOE
172    }
173
174    FileStatus[] listStatus = fs.listStatus(walPath.getParent());
175    Path rootdir = CommonFSUtils.getRootDir(conf);
176    try {
177      WALSplitter s = new WALSplitter(wals, conf, rootdir, fs, rootdir, fs, null, null, null);
178      s.splitLogFile(listStatus[0], null);
179      Path file = new Path(ZKSplitLog.getSplitLogDir(rootdir, listStatus[0].getPath().getName()),
180        "corrupt");
181      assertTrue(fs.exists(file));
182      // assertFalse("log splitting should have failed", true);
183    } catch (IOException ioe) {
184      assertTrue("WAL should have been sidelined", false);
185    }
186    wals.close();
187  }
188
189  @Test()
190  public void testSecureWALReaderOnWAL() throws Exception {
191    Configuration conf = TEST_UTIL.getConfiguration();
192    conf.setClass("hbase.regionserver.hlog.reader.impl", SecureProtobufLogReader.class,
193      WAL.Reader.class);
194    conf.setClass("hbase.regionserver.hlog.writer.impl", ProtobufLogWriter.class,
195      WALProvider.Writer.class);
196    conf.setBoolean(WAL_ENCRYPTION, false);
197    FileSystem fs = TEST_UTIL.getTestFileSystem();
198    final WALFactory wals = new WALFactory(conf, ServerName
199        .valueOf(currentTest.getMethodName(), 16010, System.currentTimeMillis()).toString());
200    Path walPath = writeWAL(wals, currentTest.getMethodName(), false);
201
202    // Ensure edits are plaintext
203    long length = fs.getFileStatus(walPath).getLen();
204    FSDataInputStream in = fs.open(walPath);
205    byte[] fileData = new byte[(int)length];
206    IOUtils.readFully(in, fileData);
207    in.close();
208    assertTrue("Cells should be plaintext", Bytes.contains(fileData, value));
209
210    // Confirm the WAL can be read back by SecureProtobufLogReader
211    try {
212      WAL.Reader reader = wals.createReader(TEST_UTIL.getTestFileSystem(), walPath);
213      reader.close();
214    } catch (IOException ioe) {
215      assertFalse(true);
216    }
217
218    FileStatus[] listStatus = fs.listStatus(walPath.getParent());
219    Path rootdir = CommonFSUtils.getRootDir(conf);
220    try {
221      WALSplitter s = new WALSplitter(wals, conf, rootdir, fs, rootdir, fs, null, null, null);
222      s.splitLogFile(listStatus[0], null);
223      Path file = new Path(ZKSplitLog.getSplitLogDir(rootdir, listStatus[0].getPath().getName()),
224        "corrupt");
225      assertTrue(!fs.exists(file));
226    } catch (IOException ioe) {
227      assertTrue("WAL should have been processed", false);
228    }
229    wals.close();
230  }
231}