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.http;
019
020import static org.junit.Assert.assertEquals;
021import static org.junit.Assert.assertNull;
022import static org.junit.Assert.fail;
023
024import java.io.IOException;
025import java.util.Random;
026import java.util.concurrent.ThreadLocalRandom;
027import javax.servlet.Filter;
028import javax.servlet.FilterChain;
029import javax.servlet.FilterConfig;
030import javax.servlet.ServletException;
031import javax.servlet.ServletRequest;
032import javax.servlet.ServletResponse;
033import javax.servlet.http.HttpServletRequest;
034import org.apache.hadoop.conf.Configuration;
035import org.apache.hadoop.hbase.HBaseClassTestRule;
036import org.apache.hadoop.hbase.testclassification.MiscTests;
037import org.apache.hadoop.hbase.testclassification.SmallTests;
038import org.apache.hadoop.net.NetUtils;
039import org.apache.hadoop.util.StringUtils;
040import org.junit.Assert;
041import org.junit.ClassRule;
042import org.junit.Ignore;
043import org.junit.Test;
044import org.junit.experimental.categories.Category;
045import org.slf4j.Logger;
046import org.slf4j.LoggerFactory;
047
048@Category({ MiscTests.class, SmallTests.class })
049public class TestServletFilter extends HttpServerFunctionalTest {
050  @ClassRule
051  public static final HBaseClassTestRule CLASS_RULE =
052    HBaseClassTestRule.forClass(TestServletFilter.class);
053
054  private static final Logger LOG = LoggerFactory.getLogger(HttpServer.class);
055  private static volatile String uri = null;
056
057  /** A very simple filter which record the uri filtered. */
058  static public class SimpleFilter implements Filter {
059    private FilterConfig filterConfig = null;
060
061    @Override
062    public void init(FilterConfig filterConfig) throws ServletException {
063      this.filterConfig = filterConfig;
064    }
065
066    @Override
067    public void destroy() {
068      this.filterConfig = null;
069    }
070
071    @Override
072    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
073      throws IOException, ServletException {
074      if (filterConfig == null) {
075        return;
076      }
077
078      uri = ((HttpServletRequest) request).getRequestURI();
079      LOG.info("filtering " + uri);
080      chain.doFilter(request, response);
081    }
082
083    /** Configuration for the filter */
084    static public class Initializer extends FilterInitializer {
085      public Initializer() {
086      }
087
088      @Override
089      public void initFilter(FilterContainer container, Configuration conf) {
090        container.addFilter("simple", SimpleFilter.class.getName(), null);
091      }
092    }
093  }
094
095  private static void assertExceptionContains(String string, Throwable t) {
096    String msg = t.getMessage();
097    Assert.assertTrue("Expected to find '" + string + "' but got unexpected exception:"
098      + StringUtils.stringifyException(t), msg.contains(string));
099  }
100
101  @Test
102  @Ignore
103  // From stack
104  // Its a 'foreign' test, one that came in from hadoop when we copy/pasted http
105  // It's second class. Could comment it out if only failing test (as per @nkeywal – sort of)
106  public void testServletFilter() throws Exception {
107    Configuration conf = new Configuration();
108
109    // start an http server with CountingFilter
110    conf.set(HttpServer.FILTER_INITIALIZERS_PROPERTY, SimpleFilter.Initializer.class.getName());
111    HttpServer http = createTestServer(conf);
112    http.start();
113
114    final String fsckURL = "/fsck";
115    final String stacksURL = "/stacks";
116    final String ajspURL = "/a.jsp";
117    final String logURL = "/logs/a.log";
118    final String hadooplogoURL = "/static/hadoop-logo.jpg";
119
120    final String[] urls = { fsckURL, stacksURL, ajspURL, logURL, hadooplogoURL };
121    final Random rand = ThreadLocalRandom.current();
122    final int[] sequence = new int[50];
123
124    // generate a random sequence and update counts
125    for (int i = 0; i < sequence.length; i++) {
126      sequence[i] = rand.nextInt(urls.length);
127    }
128
129    // access the urls as the sequence
130    final String prefix = "http://" + NetUtils.getHostPortString(http.getConnectorAddress(0));
131    try {
132      for (int aSequence : sequence) {
133        access(prefix + urls[aSequence]);
134
135        // make sure everything except fsck get filtered
136        if (aSequence == 0) {
137          assertNull(uri);
138        } else {
139          assertEquals(urls[aSequence], uri);
140          uri = null;
141        }
142      }
143    } finally {
144      http.stop();
145    }
146  }
147
148  static public class ErrorFilter extends SimpleFilter {
149    @Override
150    public void init(FilterConfig arg0) throws ServletException {
151      throw new ServletException("Throwing the exception from Filter init");
152    }
153
154    /** Configuration for the filter */
155    static public class Initializer extends FilterInitializer {
156      public Initializer() {
157      }
158
159      @Override
160      public void initFilter(FilterContainer container, Configuration conf) {
161        container.addFilter("simple", ErrorFilter.class.getName(), null);
162      }
163    }
164  }
165
166  @Test
167  public void testServletFilterWhenInitThrowsException() throws Exception {
168    Configuration conf = new Configuration();
169    // start an http server with ErrorFilter
170    conf.set(HttpServer.FILTER_INITIALIZERS_PROPERTY, ErrorFilter.Initializer.class.getName());
171    HttpServer http = createTestServer(conf);
172    try {
173      http.start();
174      fail("expecting exception");
175    } catch (IOException e) {
176      assertExceptionContains("Problem starting http server", e);
177    }
178  }
179
180  /**
181   * Similar to the above test case, except that it uses a different API to add the filter.
182   * Regression test for HADOOP-8786.
183   */
184  @Test
185  public void testContextSpecificServletFilterWhenInitThrowsException() throws Exception {
186    Configuration conf = new Configuration();
187    HttpServer http = createTestServer(conf);
188    HttpServer.defineFilter(http.webAppContext, "ErrorFilter", ErrorFilter.class.getName(), null,
189      null);
190    try {
191      http.start();
192      fail("expecting exception");
193    } catch (IOException e) {
194      assertExceptionContains("Unable to initialize WebAppContext", e);
195    }
196  }
197}