This is an automated email from the ASF dual-hosted git repository.
dkuzmenko pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/hive.git
The following commit(s) were added to refs/heads/master by this push:
new 91b65364e39 HIVE-27015: Add support to accept client connections with
X-CSRF-TOKEN as part of header in http transport mode (Taraka Rama Rao
Lethavadla, reviewed by Akshat Mathur, Denys Kuzmenko, Sai Hemanth Gantasala)
91b65364e39 is described below
commit 91b65364e398a0188eac2d2a85d8a26447bcdd09
Author: tarak271 <[email protected]>
AuthorDate: Fri Jul 28 17:33:46 2023 +0530
HIVE-27015: Add support to accept client connections with X-CSRF-TOKEN as
part of header in http transport mode (Taraka Rama Rao Lethavadla, reviewed by
Akshat Mathur, Denys Kuzmenko, Sai Hemanth Gantasala)
Closes #4428
---
.../java/org/apache/hadoop/hive/conf/HiveConf.java | 5 +-
.../java/org/apache/hive/jdbc/TestCSRFFilter.java | 171 +++++++++++++++++++++
.../org/apache/hive/jdbc/TestRestrictedList.java | 1 +
.../hive/jdbc/CsrfHttpRequestInterceptor.java | 56 +++++++
.../java/org/apache/hive/jdbc/HiveConnection.java | 3 +
.../service/cli/thrift/ThriftHttpCLIService.java | 12 ++
.../hive/service/cli/thrift/ThriftHttpFilter.java | 78 ++++++++++
.../hive/service/cli/thrift/ThriftHttpServlet.java | 9 --
.../service/cli/thrift/TestThriftHttpFilter.java | 109 +++++++++++++
.../service/cli/thrift/ThriftHttpServletTest.java | 7 +-
10 files changed, 440 insertions(+), 11 deletions(-)
diff --git a/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java
b/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java
index 294c423d665..108c545a384 100644
--- a/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java
+++ b/common/src/java/org/apache/hadoop/hive/conf/HiveConf.java
@@ -4444,6 +4444,9 @@ public class HiveConf extends Configuration {
HIVE_SERVER2_XSRF_FILTER_ENABLED("hive.server2.xsrf.filter.enabled",false,
"If enabled, HiveServer2 will block any requests made to it over http
" +
"if an X-XSRF-HEADER header is not present"),
+ HIVE_SERVER2_CSRF_FILTER_ENABLED("hive.server2.csrf.filter.enabled",false,
+ "If enabled, HiveServer2 will block any requests made to it over http
" +
+ "if an X-CSRF-TOKEN header is not present"),
HIVE_SECURITY_COMMAND_WHITELIST("hive.security.command.whitelist",
"set,reset,dfs,add,list,delete,reload,compile,llap",
"Comma separated list of non-SQL Hive commands users are authorized to
execute"),
@@ -5504,7 +5507,7 @@ public class HiveConf extends Configuration {
HIVE_CONF_RESTRICTED_LIST("hive.conf.restricted.list",
"hive.security.authenticator.manager,hive.security.authorization.manager," +
"hive.security.metastore.authorization.manager,hive.security.metastore.authenticator.manager,"
+
-
"hive.users.in.admin.role,hive.server2.xsrf.filter.enabled,hive.security.authorization.enabled,"
+
+
"hive.users.in.admin.role,hive.server2.xsrf.filter.enabled,hive.server2.csrf.filter.enabled,hive.security.authorization.enabled,"
+
"hive.distcp.privileged.doAs," +
"hive.server2.authentication.ldap.baseDN," +
"hive.server2.authentication.ldap.url," +
diff --git
a/itests/hive-unit/src/test/java/org/apache/hive/jdbc/TestCSRFFilter.java
b/itests/hive-unit/src/test/java/org/apache/hive/jdbc/TestCSRFFilter.java
new file mode 100644
index 00000000000..eff2803eb01
--- /dev/null
+++ b/itests/hive-unit/src/test/java/org/apache/hive/jdbc/TestCSRFFilter.java
@@ -0,0 +1,171 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package test.java.org.apache.hive.jdbc;
+
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
+import org.apache.hive.jdbc.CsrfHttpRequestInterceptor;
+import org.apache.hive.jdbc.miniHS2.MiniHS2;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+
+import java.io.IOException;
+import java.sql.*;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.*;
+
+/**
+ * TestCSRFFilter test.
+ */
+@RunWith(Parameterized.class)
+public class TestCSRFFilter {
+
+ private static MiniHS2 miniHS2 = null;
+ private static String dataFileDir;
+ private static Path kvDataFilePath;
+ private static final String tmpDir = System.getProperty("test.tmp.dir");
+
+ private Connection hs2Conn = null;
+
+ @Parameterized.Parameter
+ public String transportMode = null;
+
+ @Parameterized.Parameters(name = "{index}: tranportMode={0}")
+ public static Collection<Object[]> transportModes() {
+ return Arrays.asList(new Object[][]{{MiniHS2.HS2_ALL_MODE},
{MiniHS2.HS2_HTTP_MODE}});
+ }
+
+
+ @BeforeClass
+ public static void beforeClass() throws IOException {
+ MiniHS2.cleanupLocalDir();
+ }
+
+ @AfterClass
+ public static void afterClass() throws IOException {
+ MiniHS2.cleanupLocalDir();
+ }
+
+ // This is not modeled as a @Before, because it needs to be parameterized
per-test.
+ // If there is a better way to do this, we should do it.
+ private void initHS2(boolean enableCSRFFilter) throws Exception {
+ Class.forName(MiniHS2.getJdbcDriverName());
+ HiveConf conf = new HiveConf();
+ conf.setBoolVar(ConfVars.HIVE_SUPPORT_CONCURRENCY, false);
+ miniHS2 = new
MiniHS2.Builder().withConf(conf).cleanupLocalDirOnStartup(false).build();
+ dataFileDir = conf.get("test.data.files").replace('\\', '/').replace("c:",
"");
+ kvDataFilePath = new Path(dataFileDir, "kv1.txt");
+ Map<String,String> confOverlay = new HashMap<String, String>();
+ confOverlay.put(ConfVars.HIVE_SERVER2_CSRF_FILTER_ENABLED.varname,
String.valueOf(enableCSRFFilter));
+ confOverlay.put(ConfVars.HIVE_SERVER2_TRANSPORT_MODE.varname,
transportMode);
+ miniHS2.start(confOverlay);
+ }
+
+ private Connection getConnection(String jdbcURL, String user, String pwd)
throws SQLException {
+ Connection conn = DriverManager.getConnection(jdbcURL, user, pwd);
+ conn.createStatement().execute("set hive.support.concurrency = false");
+ return conn;
+ }
+
+ @After
+ public void tearDownHS2() throws Exception {
+ if (hs2Conn != null){
+ hs2Conn.close();
+ hs2Conn = null;
+ }
+ if ((miniHS2!= null) && miniHS2.isStarted()) {
+ miniHS2.stop();
+ miniHS2 = null;
+ }
+ }
+
+ @Test
+ public void testFilterDisabledNoInjection() throws Exception {
+ // filter disabled, injection disabled, exception not expected
+ runTest(false,false);
+ }
+
+ @Test
+ public void testFilterDisabledWithInjection() throws Exception {
+ // filter disabled, injection enabled, exception not expected
+ runTest(false,true);
+ }
+
+ @Test
+ public void testFilterEnabledWithInjection() throws Exception {
+ // filter enabled, injection enabled, exception not expected
+ runTest(true,true);
+ }
+
+ @Test
+ public void testFilterEnabledNoInjection() throws Exception {
+ // filter enabled, injection disabled, exception expected
+ runTest(true,false);
+ }
+
+ private void runTest(boolean isFilterEnabled, boolean isInjectionEnabled)
throws Exception {
+ // Exception is expected only if filter is enabled and injection is
disabled
+ boolean exceptionExpected = isFilterEnabled && (!isInjectionEnabled);
+ initHS2(isFilterEnabled);
+ CsrfHttpRequestInterceptor.setInjectHeader(isInjectionEnabled);
+ Exception e = null;
+ try {
+ runBasicCommands();
+ } catch (Exception thrown) {
+ e = thrown;
+ }
+ if (exceptionExpected){
+ assertNotNull(e);
+ } else {
+ assertEquals(null,e);
+ }
+ }
+
+
+ private void runBasicCommands() throws Exception {
+ hs2Conn = getConnection(miniHS2.getHttpJdbcURL(),
System.getProperty("user.name"), "bar");
+ String tableName = "testTab1";
+ Statement stmt = hs2Conn.createStatement();
+
+ // create table
+ stmt.execute("DROP TABLE IF EXISTS " + tableName);
+ stmt.execute("CREATE TABLE " + tableName
+ + " (under_col INT COMMENT 'the under column', value STRING) COMMENT '
test table'");
+
+ // load data
+ stmt.execute("load data local inpath '"
+ + kvDataFilePath.toString() + "' into table " + tableName);
+
+ ResultSet res = stmt.executeQuery("SELECT * FROM " + tableName);
+ assertTrue(res.next());
+ assertEquals("val_238", res.getString(2));
+ res.close();
+ stmt.close();
+ }
+
+}
diff --git
a/itests/hive-unit/src/test/java/org/apache/hive/jdbc/TestRestrictedList.java
b/itests/hive-unit/src/test/java/org/apache/hive/jdbc/TestRestrictedList.java
index 1b37a33e099..04780ad0546 100644
---
a/itests/hive-unit/src/test/java/org/apache/hive/jdbc/TestRestrictedList.java
+++
b/itests/hive-unit/src/test/java/org/apache/hive/jdbc/TestRestrictedList.java
@@ -76,6 +76,7 @@ public class TestRestrictedList {
addToExpectedRestrictedMap("hive.security.metastore.authenticator.manager");
addToExpectedRestrictedMap("hive.users.in.admin.role");
addToExpectedRestrictedMap("hive.server2.xsrf.filter.enabled");
+ addToExpectedRestrictedMap("hive.server2.csrf.filter.enabled");
addToExpectedRestrictedMap("hive.security.authorization.enabled");
addToExpectedRestrictedMap("hive.distcp.privileged.doAs");
addToExpectedRestrictedMap("hive.server2.authentication.ldap.baseDN");
diff --git a/jdbc/src/java/org/apache/hive/jdbc/CsrfHttpRequestInterceptor.java
b/jdbc/src/java/org/apache/hive/jdbc/CsrfHttpRequestInterceptor.java
new file mode 100644
index 00000000000..e23df76ac49
--- /dev/null
+++ b/jdbc/src/java/org/apache/hive/jdbc/CsrfHttpRequestInterceptor.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hive.jdbc;
+
+import org.apache.http.HttpException;
+import org.apache.http.HttpRequest;
+import org.apache.http.HttpRequestInterceptor;
+import org.apache.http.protocol.HttpContext;
+
+import java.io.IOException;
+
+public class CsrfHttpRequestInterceptor implements HttpRequestInterceptor {
+
+ // Note : This implements HttpRequestInterceptor rather than extending
+ // HttpRequestInterceptorBase, because that class is an auth-specific
+ // class and refactoring would kludge too many things that are potentially
+ // public api.
+ //
+ // At the base, though, what we do is a very simple thing to protect
+ // against CSRF attacks, and that is to simply add another header. If
+ // HS2 is running with an CSRF filter enabled, then it will reject all
+ // requests that do not contain this. Thus, we add this in here on the
+ // client-side. This simple check prevents random other websites from
+ // redirecting a browser that has login credentials from making a
+ // request to HS2 on their behalf.
+
+ private static boolean injectHeader = true;
+
+ public static void setInjectHeader(boolean headerInjection){
+ injectHeader = headerInjection;
+ }
+
+ @Override
+ public void process(HttpRequest httpRequest, HttpContext httpContext)
+ throws HttpException, IOException {
+ if (injectHeader){
+ httpRequest.addHeader("X-CSRF-TOKEN", "true");
+ }
+ }
+}
diff --git a/jdbc/src/java/org/apache/hive/jdbc/HiveConnection.java
b/jdbc/src/java/org/apache/hive/jdbc/HiveConnection.java
index 21c6feea50f..5850105b5fa 100644
--- a/jdbc/src/java/org/apache/hive/jdbc/HiveConnection.java
+++ b/jdbc/src/java/org/apache/hive/jdbc/HiveConnection.java
@@ -767,6 +767,9 @@ public class HiveConnection implements java.sql.Connection {
// Add an interceptor to add in an XSRF header
httpClientBuilder.addInterceptorLast(new XsrfHttpRequestInterceptor());
+ // Add an interceptor to add in a CSRF header
+ httpClientBuilder.addInterceptorLast(new CsrfHttpRequestInterceptor());
+
// set the specified timeout (socketTimeout jdbc param) for http
connection as well
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(loginTimeout * 1000)
diff --git
a/service/src/java/org/apache/hive/service/cli/thrift/ThriftHttpCLIService.java
b/service/src/java/org/apache/hive/service/cli/thrift/ThriftHttpCLIService.java
index 1e573cc87cc..bc20ea7797e 100644
---
a/service/src/java/org/apache/hive/service/cli/thrift/ThriftHttpCLIService.java
+++
b/service/src/java/org/apache/hive/service/cli/thrift/ThriftHttpCLIService.java
@@ -20,6 +20,7 @@ package org.apache.hive.service.cli.thrift;
import java.security.KeyStore;
import java.util.Arrays;
+import java.util.EnumSet;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
@@ -27,6 +28,7 @@ import java.util.concurrent.TimeUnit;
import java.util.Set;
import javax.net.ssl.KeyManagerFactory;
+import javax.servlet.DispatcherType;
import javax.ws.rs.HttpMethod;
import com.google.common.base.Splitter;
@@ -62,6 +64,7 @@ import org.eclipse.jetty.server.HttpConnectionFactory;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.gzip.GzipHandler;
+import org.eclipse.jetty.servlet.FilterHolder;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.security.Constraint;
@@ -227,6 +230,10 @@ public class ThriftHttpCLIService extends ThriftCLIService
{
server.setHandler(context);
}
context.addServlet(new ServletHolder(thriftHttpServlet), httpPath);
+ if(isHttpFilteringEnabled(hiveConf)){
+ ThriftHttpFilter thriftHttpFilter = new ThriftHttpFilter(hiveConf);
+ context.addFilter(new FilterHolder(thriftHttpFilter),httpPath,
EnumSet.of(DispatcherType.REQUEST));
+ }
if (AuthType.isSamlAuthMode(hiveConf)) {
String ssoPath = HiveSamlUtils.getCallBackPath(hiveConf);
context.addServlet(new ServletHolder(new
HiveSamlHttpServlet(hiveConf)), ssoPath);
@@ -309,6 +316,11 @@ public class ThriftHttpCLIService extends ThriftCLIService
{
return httpPath;
}
+ public boolean isHttpFilteringEnabled(HiveConf hiveConf){
+ return
hiveConf.getBoolean(HiveConf.ConfVars.HIVE_SERVER2_XSRF_FILTER_ENABLED.varname,
false) ||
+
hiveConf.getBoolean(HiveConf.ConfVars.HIVE_SERVER2_CSRF_FILTER_ENABLED.varname,
false);
+ }
+
public void constrainHttpMethods(ServletContextHandler ctxHandler, boolean
allowOptionsMethod) {
Constraint c = new Constraint();
c.setAuthenticate(true);
diff --git
a/service/src/java/org/apache/hive/service/cli/thrift/ThriftHttpFilter.java
b/service/src/java/org/apache/hive/service/cli/thrift/ThriftHttpFilter.java
new file mode 100644
index 00000000000..5179130e0e1
--- /dev/null
+++ b/service/src/java/org/apache/hive/service/cli/thrift/ThriftHttpFilter.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.hive.service.cli.thrift;
+
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hadoop.hive.shims.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.FilterChain;
+import javax.servlet.http.HttpServletResponse;
+import java.io.IOException;
+
+public class ThriftHttpFilter implements Filter {
+
+ public static final Logger LOG =
LoggerFactory.getLogger(ThriftHttpFilter.class.getName());
+ protected static final String X_CSRF_TOKEN = "X-CSRF-TOKEN";
+ protected static final String X_XSRF_HEADER = "X-XSRF-HEADER";
+
+ protected static final String ERROR_MESSAGE = "Request did not have valid
XSRF header/CSRF token, rejecting.";
+
+ protected HiveConf hiveConf;
+
+ public ThriftHttpFilter(HiveConf hiveConf) {
+ super();
+ this.hiveConf = hiveConf;
+ }
+
+ @Override
+ public void init(FilterConfig filterConfig) throws ServletException {
+ // As of now no action is needed in this method
+ }
+
+ @Override
+ public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain)
+ throws IOException, ServletException {
+ boolean xsrfFlag =
this.hiveConf.getBoolean(HiveConf.ConfVars.HIVE_SERVER2_XSRF_FILTER_ENABLED.varname,
false);
+ boolean csrfFlag =
this.hiveConf.getBoolean(HiveConf.ConfVars.HIVE_SERVER2_CSRF_FILTER_ENABLED.varname,
false);
+ if (LOG.isDebugEnabled()) {
+ LOG.debug("Is {} filtering Enabled : {}", X_CSRF_TOKEN, csrfFlag);
+ LOG.debug("Is {} filtering Enabled : {}", X_XSRF_HEADER, xsrfFlag);
+ }
+ if ((!xsrfFlag && !csrfFlag) ||
+ (csrfFlag && Utils.doXsrfFilter(request, response, null,
X_CSRF_TOKEN)) ||
+ (xsrfFlag && Utils.doXsrfFilter(request, response, null,
X_XSRF_HEADER))) {
+ filterChain.doFilter(request, response);
+ } else {
+ LOG.warn(ERROR_MESSAGE);
+
((HttpServletResponse)response).sendError(HttpServletResponse.SC_FORBIDDEN,
ERROR_MESSAGE);
+ }
+ }
+
+ @Override
+ public void destroy() {
+ // As of now no action is needed in this method
+ }
+}
diff --git
a/service/src/java/org/apache/hive/service/cli/thrift/ThriftHttpServlet.java
b/service/src/java/org/apache/hive/service/cli/thrift/ThriftHttpServlet.java
index 100f5f00ce4..263ac3a6092 100644
--- a/service/src/java/org/apache/hive/service/cli/thrift/ThriftHttpServlet.java
+++ b/service/src/java/org/apache/hive/service/cli/thrift/ThriftHttpServlet.java
@@ -113,7 +113,6 @@ public class ThriftHttpServlet extends TServlet {
private static final String HIVE_DELEGATION_TOKEN_HEADER =
"X-Hive-Delegation-Token";
private static final String X_FORWARDED_FOR = "X-Forwarded-For";
private static final String AUTH_TYPE = "auth";
-
private JWTValidator jwtValidator;
public ThriftHttpServlet(TProcessor processor, TProtocolFactory
protocolFactory,
@@ -153,17 +152,9 @@ public class ThriftHttpServlet extends TServlet {
String clientUserName = null;
String clientIpAddress;
boolean requireNewCookie = false;
-
logTrackingHeaderIfAny(request);
try {
- if
(hiveConf.getBoolean(ConfVars.HIVE_SERVER2_XSRF_FILTER_ENABLED.varname,false)){
- boolean continueProcessing =
Utils.doXsrfFilter(request,response,null,null);
- if (!continueProcessing){
- LOG.warn("Request did not have valid XSRF header, rejecting.");
- return;
- }
- }
clientIpAddress = request.getRemoteAddr();
LOG.debug("Client IP Address: " + clientIpAddress);
diff --git
a/service/src/test/org/apache/hive/service/cli/thrift/TestThriftHttpFilter.java
b/service/src/test/org/apache/hive/service/cli/thrift/TestThriftHttpFilter.java
new file mode 100644
index 00000000000..ee957901ad4
--- /dev/null
+++
b/service/src/test/org/apache/hive/service/cli/thrift/TestThriftHttpFilter.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.apache.hive.service.cli.thrift;
+
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.mockito.Mockito;
+
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.*;
+import java.util.Arrays;
+import java.util.Collection;
+
+@RunWith(Parameterized.class)
+public class TestThriftHttpFilter {
+
+ @Parameterized.Parameter
+ public String filterName;
+
+ @Parameterized.Parameter(1)
+ public boolean isFilterEnabled;
+
+ @Parameterized.Parameter(2)
+ public String headerName;
+
+ @Parameterized.Parameter(3)
+ public boolean isHeaderSent;
+
+ @Parameterized.Parameter(4)
+ public int invokeFilterChaining;
+ private HiveConf hiveConf;
+ private HttpServletRequest httpServletRequest;
+ private HttpServletResponse httpServletResponse;
+ private FilterChain filterChain;
+ private FilterConfig filterConfig;
+
+ @Parameterized.Parameters(name = "{index}:
filterName={0},isFilteringEnabled={1},headerName={2},isHeaderSent={3},invokeFilterChaining={4}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][] {
+ { HiveConf.ConfVars.HIVE_SERVER2_XSRF_FILTER_ENABLED.varname, true,
ThriftHttpFilter.X_XSRF_HEADER, true, 1 },
+ { HiveConf.ConfVars.HIVE_SERVER2_XSRF_FILTER_ENABLED.varname, true,
ThriftHttpFilter.X_XSRF_HEADER, false, 0 },
+ { HiveConf.ConfVars.HIVE_SERVER2_XSRF_FILTER_ENABLED.varname, false,
ThriftHttpFilter.X_XSRF_HEADER, true, 1 },
+ { HiveConf.ConfVars.HIVE_SERVER2_XSRF_FILTER_ENABLED.varname, false,
ThriftHttpFilter.X_XSRF_HEADER, false, 1 },
+ { HiveConf.ConfVars.HIVE_SERVER2_CSRF_FILTER_ENABLED.varname, true,
ThriftHttpFilter.X_CSRF_TOKEN, true, 1 },
+ { HiveConf.ConfVars.HIVE_SERVER2_CSRF_FILTER_ENABLED.varname, true,
ThriftHttpFilter.X_CSRF_TOKEN, false, 0 },
+ { HiveConf.ConfVars.HIVE_SERVER2_CSRF_FILTER_ENABLED.varname, false,
ThriftHttpFilter.X_CSRF_TOKEN, true, 1 },
+ { HiveConf.ConfVars.HIVE_SERVER2_CSRF_FILTER_ENABLED.varname, false,
ThriftHttpFilter.X_CSRF_TOKEN, false, 1 }
+ });
+ }
+
+ @Before
+ public void setup() throws IOException {
+ hiveConf = new HiveConf();
+ httpServletRequest = Mockito.mock(HttpServletRequest.class);
+ httpServletResponse = Mockito.mock(HttpServletResponse.class);
+ filterChain = Mockito.mock(FilterChain.class);
+ filterConfig = Mockito.mock(FilterConfig.class);
+ Mockito.when(httpServletRequest.getRequestURI()).thenReturn("/cliservice");
+ PrintWriter printWriter = Mockito.mock(PrintWriter.class);
+ Mockito.when(httpServletResponse.getWriter()).thenReturn(printWriter);
+ }
+
+ private void executeFilter() throws ServletException, IOException {
+ ThriftHttpFilter thriftHttpFilter = new ThriftHttpFilter(hiveConf);
+ thriftHttpFilter.init(filterConfig);
+ thriftHttpFilter.doFilter(httpServletRequest, httpServletResponse,
filterChain);
+ thriftHttpFilter.destroy();
+ }
+
+ private void initializeFilter() {
+ hiveConf.setBoolean(filterName, isFilterEnabled);
+ if (isHeaderSent) {
+
Mockito.when(httpServletRequest.getHeader(headerName)).thenReturn(headerName);
+ } else {
+ Mockito.when(httpServletRequest.getHeader(headerName)).thenReturn(null);
+ }
+ }
+
+ @Test
+ public void testFilter() throws ServletException, IOException {
+ initializeFilter();
+ executeFilter();
+ Mockito.verify(filterChain,
Mockito.times(invokeFilterChaining)).doFilter(httpServletRequest,
httpServletResponse);
+ }
+}
diff --git
a/service/src/test/org/apache/hive/service/cli/thrift/ThriftHttpServletTest.java
b/service/src/test/org/apache/hive/service/cli/thrift/ThriftHttpServletTest.java
index 28ff60ecb1f..02b24dd846b 100644
---
a/service/src/test/org/apache/hive/service/cli/thrift/ThriftHttpServletTest.java
+++
b/service/src/test/org/apache/hive/service/cli/thrift/ThriftHttpServletTest.java
@@ -21,6 +21,7 @@ import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hive.service.auth.HiveAuthConstants;
import org.apache.hive.service.auth.HttpAuthUtils;
import org.apache.hive.service.auth.ldap.HttpEmptyAuthenticationException;
+import org.junit.Assert;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@@ -31,6 +32,8 @@ import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.io.PrintWriter;
/**
* ThriftHttpServletTest.
@@ -42,9 +45,10 @@ public class ThriftHttpServletTest {
private ThriftHttpServlet thriftHttpServlet;
+ private HiveConf hiveConf = new HiveConf();
+
@Before
public void setUp() throws Exception {
- HiveConf hiveConf = new HiveConf();
String authType = HiveAuthConstants.AuthTypes.KERBEROS.toString();
hiveConf.setVar(HiveConf.ConfVars.HIVE_SERVER2_AUTHENTICATION, authType);
thriftHttpServlet = new ThriftHttpServlet(null, null, null, null, null,
hiveConf);
@@ -71,4 +75,5 @@ public class ThriftHttpServletTest {
"from the client is empty.");
thriftHttpServlet.doKerberosAuth(httpServletRequest);
}
+
}