This is an automated email from the ASF dual-hosted git repository.

dengzh 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 3cd8fd386b7 HIVE-27661: Authentication mode inferred from the 
Authorization header (#4666) (Gergely Farkas, reviewed by Zhihua Deng)
3cd8fd386b7 is described below

commit 3cd8fd386b740b7037d6dfa3e90510e1fca1d1b7
Author: Gergely Farkas <[email protected]>
AuthorDate: Fri Sep 8 11:20:53 2023 +0200

    HIVE-27661: Authentication mode inferred from the Authorization header 
(#4666) (Gergely Farkas, reviewed by Zhihua Deng)
---
 .../apache/hive/minikdc/TestIsAuthTypeEnabled.java | 267 +++++++++++++++++++++
 .../apache/hive/jdbc/HttpBasicAuthInterceptor.java |   6 -
 .../hive/jdbc/HttpKerberosRequestInterceptor.java  |   5 -
 .../hive/jdbc/HttpRequestInterceptorBase.java      |   9 -
 .../apache/hive/jdbc/HttpTokenAuthInterceptor.java |   6 -
 .../jdbc/jwt/HttpJwtAuthRequestInterceptor.java    |   5 -
 .../jdbc/saml/HttpSamlAuthRequestInterceptor.java  |   5 -
 .../org/apache/hive/service/auth/AuthType.java     |   7 -
 .../hive/service/cli/thrift/ThriftHttpServlet.java |  81 ++++---
 .../org/apache/hive/service/auth/TestAuthType.java |   5 -
 10 files changed, 319 insertions(+), 77 deletions(-)

diff --git 
a/itests/hive-minikdc/src/test/java/org/apache/hive/minikdc/TestIsAuthTypeEnabled.java
 
b/itests/hive-minikdc/src/test/java/org/apache/hive/minikdc/TestIsAuthTypeEnabled.java
new file mode 100644
index 00000000000..1a93711d61f
--- /dev/null
+++ 
b/itests/hive-minikdc/src/test/java/org/apache/hive/minikdc/TestIsAuthTypeEnabled.java
@@ -0,0 +1,267 @@
+/*
+ * 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.minikdc;
+
+import com.github.tomakehurst.wiremock.junit.WireMockRule;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import org.apache.hadoop.hive.conf.HiveConf;
+import org.apache.hive.service.auth.HttpAuthUtils;
+import org.apache.hive.service.auth.saml.HiveSamlUtils;
+import org.apache.hive.service.cli.thrift.ThriftHttpServlet;
+import org.junit.Before;
+import org.junit.ClassRule;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+import javax.servlet.http.HttpServletRequest;
+
+import java.io.File;
+import java.nio.file.Files;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.stream.Collectors;
+
+import static com.github.tomakehurst.wiremock.client.WireMock.get;
+import static com.github.tomakehurst.wiremock.client.WireMock.ok;
+import static org.apache.hive.service.auth.HiveAuthConstants.AuthTypes;
+import static 
org.apache.hive.service.cli.thrift.ThriftHttpServlet.HIVE_DELEGATION_TOKEN_HEADER;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * Tests the logic that determines whether a given authentication mode
+ * should be checked based on the Authorization header.
+ */
+public class TestIsAuthTypeEnabled {
+
+  private static final int MOCK_JWKS_SERVER_PORT = 8089;
+  private static final File jwtVerificationJWKSFile =
+    new File("src/test/resources/auth.jwt/jwt-verification-jwks.json");
+
+  @ClassRule
+  public static final WireMockRule MOCK_JWKS_SERVER = new 
WireMockRule(MOCK_JWKS_SERVER_PORT);
+
+  @Before
+  public void setUp() throws Exception {
+    MOCK_JWKS_SERVER.stubFor(get("/jwks")
+      .willReturn(ok()
+        .withBody(Files.readAllBytes(jwtVerificationJWKSFile.toPath()))));
+  }
+
+  @Test
+  public void testIsAuthTypeEnabled() throws Exception {
+
+    assertTrue(
+      // isAuthTypeEnabled should be true when Kerberos authentication is 
enabled
+      // and Kerberos authentication is initiated with "Authorization: 
Negotiate ..." header
+      createThriftHttpServletWithAuthTypes(
+        ImmutableList.of(AuthTypes.LDAP, AuthTypes.KERBEROS, AuthTypes.SAML)
+      ).isAuthTypeEnabled(
+        
createMockHttpServletRequest(ImmutableMap.of(HttpAuthUtils.AUTHORIZATION,
+          Optional.of("Negotiate anyToken"))),
+        AuthTypes.KERBEROS
+      )
+    );
+
+    assertFalse(
+      // isAuthTypeEnabled should be false when Kerberos authentication is 
disabled
+      // and Kerberos authentication is initiated with "Authorization: 
Negotiate ..." header
+      createThriftHttpServletWithAuthTypes(
+        ImmutableList.of(AuthTypes.SAML, AuthTypes.LDAP)
+      ).isAuthTypeEnabled(
+        
createMockHttpServletRequest(ImmutableMap.of(HttpAuthUtils.AUTHORIZATION,
+          Optional.of("Negotiate anyToken"))),
+        AuthTypes.KERBEROS
+      )
+    );
+
+    assertTrue(
+      // isAuthTypeEnabled should be true when Kerberos authentication is 
enabled
+      // and delegation token received in X-Hive-Delegation-Token header
+      createThriftHttpServletWithAuthTypes(
+        ImmutableList.of(AuthTypes.LDAP, AuthTypes.KERBEROS, AuthTypes.SAML)
+      ).isAuthTypeEnabled(
+        
createMockHttpServletRequest(ImmutableMap.of(HIVE_DELEGATION_TOKEN_HEADER,
+          Optional.of("any Hive delegation token"))),
+        AuthTypes.KERBEROS
+      )
+    );
+
+    assertFalse(
+      // isAuthTypeEnabled should be false when Kerberos authentication is 
disabled
+      // and delegation token received in X-Hive-Delegation-Token header
+      createThriftHttpServletWithAuthTypes(
+        ImmutableList.of(AuthTypes.SAML, AuthTypes.LDAP)
+      ).isAuthTypeEnabled(
+        
createMockHttpServletRequest(ImmutableMap.of(HIVE_DELEGATION_TOKEN_HEADER,
+          Optional.of("any Hive delegation token"))),
+        AuthTypes.KERBEROS
+      )
+    );
+
+    assertTrue(
+      // isAuthTypeEnabled should be true when JWT authentication is enabled
+      // and JWT authentication is initiated with "Authorization: Bearer 
jwt...token" header
+      createThriftHttpServletWithAuthTypes(
+        ImmutableList.of(AuthTypes.KERBEROS, AuthTypes.JWT, AuthTypes.SAML, 
AuthTypes.LDAP)
+      ).isAuthTypeEnabled(
+        
createMockHttpServletRequest(ImmutableMap.of(HttpAuthUtils.AUTHORIZATION,
+          Optional.of("Bearer any.jwt.token"))),
+        AuthTypes.JWT
+      )
+    );
+
+    assertFalse(
+      // isAuthTypeEnabled should be false when JWT authentication is disabled
+      // and JWT authentication is initiated with "Authorization: Bearer 
jwt...token" header
+      createThriftHttpServletWithAuthTypes(
+        ImmutableList.of(AuthTypes.KERBEROS, AuthTypes.SAML, AuthTypes.LDAP)
+      ).isAuthTypeEnabled(
+        
createMockHttpServletRequest(ImmutableMap.of(HttpAuthUtils.AUTHORIZATION,
+          Optional.of("Bearer any.jwt.token"))),
+        AuthTypes.JWT
+      )
+    );
+
+    assertTrue(
+      // isAuthTypeEnabled should be true when SAML authentication is enabled
+      // and SAML authentication is initiated with "Authorization: Bearer 
saml.token" header
+      createThriftHttpServletWithAuthTypes(
+        ImmutableList.of(AuthTypes.KERBEROS, AuthTypes.SAML, AuthTypes.LDAP)
+      ).isAuthTypeEnabled(
+        
createMockHttpServletRequest(ImmutableMap.of(HttpAuthUtils.AUTHORIZATION,
+          Optional.of("Bearer anySamlToken"))),
+        AuthTypes.SAML
+      )
+    );
+
+    assertFalse(
+      // isAuthTypeEnabled should be false when SAML authentication is disabled
+      // and SAML authentication is initiated with "Authorization: Bearer 
saml.token" header
+      createThriftHttpServletWithAuthTypes(
+        ImmutableList.of(AuthTypes.KERBEROS, AuthTypes.LDAP)
+      ).isAuthTypeEnabled(
+        
createMockHttpServletRequest(ImmutableMap.of(HttpAuthUtils.AUTHORIZATION,
+          Optional.of("Bearer anySamlToken"))),
+        AuthTypes.SAML
+      )
+    );
+
+    assertTrue(
+      // isAuthTypeEnabled should be true when SAML authentication is enabled,
+      // no "Authorization" header received, but X-Hive-Token-Response-Port 
header
+      // indicates SAML authentication
+      createThriftHttpServletWithAuthTypes(
+        ImmutableList.of(AuthTypes.KERBEROS, AuthTypes.SAML, AuthTypes.LDAP)
+      ).isAuthTypeEnabled(
+        
createMockHttpServletRequest(ImmutableMap.of(HiveSamlUtils.SSO_TOKEN_RESPONSE_PORT,
+          Optional.of("4321"))),
+        AuthTypes.SAML
+      )
+    );
+
+    assertFalse(
+      // isAuthTypeEnabled should be false when SAML authentication is 
disabled,
+      // no "Authorization" header received and X-Hive-Token-Response-Port 
header
+      // is present
+      createThriftHttpServletWithAuthTypes(
+        ImmutableList.of(AuthTypes.KERBEROS, AuthTypes.LDAP)
+      ).isAuthTypeEnabled(
+        
createMockHttpServletRequest(ImmutableMap.of(HiveSamlUtils.SSO_TOKEN_RESPONSE_PORT,
+          Optional.of("4321"))),
+        AuthTypes.SAML
+      )
+    );
+
+    assertTrue(
+      // isAuthTypeEnabled should be true when LDAP authentication is enabled
+      // and LDAP authentication is initiated with "Authorization: Basic ..." 
header
+      createThriftHttpServletWithAuthTypes(
+        ImmutableList.of(AuthTypes.KERBEROS, AuthTypes.SAML, AuthTypes.LDAP)
+      ).isAuthTypeEnabled(
+        
createMockHttpServletRequest(ImmutableMap.of(HttpAuthUtils.AUTHORIZATION,
+          Optional.of("Basic base64EncodedCredentials"))),
+        AuthTypes.LDAP
+      )
+    );
+
+    assertFalse(
+      // isAuthTypeEnabled should be false when LDAP authentication is disabled
+      // and LDAP authentication is initiated with "Authorization: Basic ..." 
header
+      createThriftHttpServletWithAuthTypes(
+        ImmutableList.of(AuthTypes.KERBEROS, AuthTypes.SAML)
+      ).isAuthTypeEnabled(
+        
createMockHttpServletRequest(ImmutableMap.of(HttpAuthUtils.AUTHORIZATION,
+          Optional.of("Basic base64EncodedCredentials"))),
+        AuthTypes.LDAP
+      )
+    );
+
+    assertFalse(
+      // isAuthTypeEnabled should be false when JWT authentication is enabled
+      // but there is no JWT token in the Authorization header
+      createThriftHttpServletWithAuthTypes(
+        ImmutableList.of(AuthTypes.JWT, AuthTypes.SAML, AuthTypes.LDAP)
+      ).isAuthTypeEnabled(
+        createMockHttpServletRequest(),
+        AuthTypes.JWT
+      )
+    );
+
+    assertFalse(
+      // isAuthTypeEnabled should be false when JWT authentication is enabled
+      // but checking Kerberos authentication
+      createThriftHttpServletWithAuthTypes(
+        ImmutableList.of(AuthTypes.JWT, AuthTypes.SAML, AuthTypes.LDAP, 
AuthTypes.KERBEROS)
+      ).isAuthTypeEnabled(
+        createMockHttpServletRequest(),
+        AuthTypes.KERBEROS
+      )
+    );
+
+  }
+
+  private HttpServletRequest createMockHttpServletRequest() {
+    return createMockHttpServletRequest(ImmutableMap.of());
+  }
+
+  private HttpServletRequest createMockHttpServletRequest(Map<String, 
Optional<String>> headers) {
+    HttpServletRequest httpServletRequest = 
Mockito.mock(HttpServletRequest.class);
+    headers.entrySet().stream().forEach(
+      entry -> Mockito
+        .when(httpServletRequest.getHeader(entry.getKey()))
+        .thenReturn(entry.getValue().orElse(null))
+    );
+    return httpServletRequest;
+  }
+
+  private ThriftHttpServlet 
createThriftHttpServletWithAuthTypes(List<AuthTypes> authTypesList)
+          throws Exception {
+    HiveConf hiveConf = new HiveConf();
+    String authType = authTypesList.stream().map(Object::toString)
+      .collect(Collectors.joining(","));
+    hiveConf.setVar(HiveConf.ConfVars.HIVE_SERVER2_AUTHENTICATION, authType);
+    // the content of the URL below is the same as jwtVerificationJWKSFile
+    hiveConf.setVar(HiveConf.ConfVars.HIVE_SERVER2_AUTHENTICATION_JWT_JWKS_URL,
+  "http://localhost:"; + MOCK_JWKS_SERVER_PORT + "/jwks");
+    return new ThriftHttpServlet(null, null, null, null, null, hiveConf);
+  }
+}
diff --git a/jdbc/src/java/org/apache/hive/jdbc/HttpBasicAuthInterceptor.java 
b/jdbc/src/java/org/apache/hive/jdbc/HttpBasicAuthInterceptor.java
index 1602ba7aa44..1887e07b19d 100644
--- a/jdbc/src/java/org/apache/hive/jdbc/HttpBasicAuthInterceptor.java
+++ b/jdbc/src/java/org/apache/hive/jdbc/HttpBasicAuthInterceptor.java
@@ -53,10 +53,4 @@ public class HttpBasicAuthInterceptor extends 
HttpRequestInterceptorBase {
     Header basicAuthHeader = authScheme.authenticate(credentials, httpRequest, 
httpContext);
     httpRequest.addHeader(basicAuthHeader);
   }
-
-  @Override
-  protected String getAuthType() {
-    // Let the server determine which particular password based method is 
using.
-    return "UIDPWD";
-  }
 }
\ No newline at end of file
diff --git 
a/jdbc/src/java/org/apache/hive/jdbc/HttpKerberosRequestInterceptor.java 
b/jdbc/src/java/org/apache/hive/jdbc/HttpKerberosRequestInterceptor.java
index c211260589b..bff6fd65806 100644
--- a/jdbc/src/java/org/apache/hive/jdbc/HttpKerberosRequestInterceptor.java
+++ b/jdbc/src/java/org/apache/hive/jdbc/HttpKerberosRequestInterceptor.java
@@ -70,9 +70,4 @@ public class HttpKerberosRequestInterceptor extends 
HttpRequestInterceptorBase {
       kerberosLock.unlock();
     }
   }
-
-  @Override
-  protected String getAuthType() {
-    return "KERBEROS";
-  }
 }
\ No newline at end of file
diff --git a/jdbc/src/java/org/apache/hive/jdbc/HttpRequestInterceptorBase.java 
b/jdbc/src/java/org/apache/hive/jdbc/HttpRequestInterceptorBase.java
index 10b7246af47..862d299643e 100644
--- a/jdbc/src/java/org/apache/hive/jdbc/HttpRequestInterceptorBase.java
+++ b/jdbc/src/java/org/apache/hive/jdbc/HttpRequestInterceptorBase.java
@@ -21,7 +21,6 @@ package org.apache.hive.jdbc;
 import java.io.IOException;
 import java.util.HashMap;
 import java.util.Map;
-import java.util.Objects;
 import java.util.concurrent.atomic.AtomicLong;
 import java.util.function.Supplier;
 import org.apache.hadoop.hive.conf.Constants;
@@ -52,13 +51,6 @@ public abstract class HttpRequestInterceptorBase implements 
HttpRequestIntercept
   protected abstract void addHttpAuthHeader(HttpRequest httpRequest, 
HttpContext httpContext)
     throws Exception;
 
-  /**
-   * The auth method to tell the server to choose right auth mechanism to
-   * validate the request, especially when the server supports multiple auth 
methods in parallel.
-   * @return the auth method the client is using, should not be null or empty
-   */
-  protected abstract String getAuthType();
-
   public HttpRequestInterceptorBase(CookieStore cs, String cn, boolean isSSL,
       Map<String, String> additionalHeaders, Map<String, String> 
customCookies) {
     this.cookieStore = cs;
@@ -111,7 +103,6 @@ public abstract class HttpRequestInterceptorBase implements 
HttpRequestIntercept
           httpRequest.addHeader(entry.getKey(), entry.getValue());
         }
       }
-      httpRequest.addHeader(Utils.JdbcConnectionParams.AUTH_TYPE, 
Objects.requireNonNull(getAuthType()));
       // Add custom cookies if passed to the jdbc driver
       if (customCookies != null) {
         String cookieHeaderKeyValues = "";
diff --git a/jdbc/src/java/org/apache/hive/jdbc/HttpTokenAuthInterceptor.java 
b/jdbc/src/java/org/apache/hive/jdbc/HttpTokenAuthInterceptor.java
index 4c903880841..fbfa7f6d5a6 100644
--- a/jdbc/src/java/org/apache/hive/jdbc/HttpTokenAuthInterceptor.java
+++ b/jdbc/src/java/org/apache/hive/jdbc/HttpTokenAuthInterceptor.java
@@ -44,10 +44,4 @@ public class HttpTokenAuthInterceptor extends 
HttpRequestInterceptorBase {
     throws Exception {
     httpRequest.addHeader(HIVE_DELEGATION_TOKEN_HEADER, tokenStr);
   }
-
-  @Override
-  protected String getAuthType() {
-    // The auth token is Kerberos based
-    return "KERBEROS";
-  }
 }
\ No newline at end of file
diff --git 
a/jdbc/src/java/org/apache/hive/jdbc/jwt/HttpJwtAuthRequestInterceptor.java 
b/jdbc/src/java/org/apache/hive/jdbc/jwt/HttpJwtAuthRequestInterceptor.java
index 917bc983526..51390c686b8 100644
--- a/jdbc/src/java/org/apache/hive/jdbc/jwt/HttpJwtAuthRequestInterceptor.java
+++ b/jdbc/src/java/org/apache/hive/jdbc/jwt/HttpJwtAuthRequestInterceptor.java
@@ -46,9 +46,4 @@ public class HttpJwtAuthRequestInterceptor extends 
HttpRequestInterceptorBase {
   protected void addHttpAuthHeader(HttpRequest httpRequest, HttpContext 
httpContext) {
     httpRequest.addHeader(HttpHeaders.AUTHORIZATION, HttpAuthUtils.BEARER + " 
" + signedJwt);
   }
-
-  @Override
-  protected String getAuthType() {
-    return "JWT";
-  }
 }
diff --git 
a/jdbc/src/java/org/apache/hive/jdbc/saml/HttpSamlAuthRequestInterceptor.java 
b/jdbc/src/java/org/apache/hive/jdbc/saml/HttpSamlAuthRequestInterceptor.java
index 1e2bc429bbe..430dc8d0ef0 100644
--- 
a/jdbc/src/java/org/apache/hive/jdbc/saml/HttpSamlAuthRequestInterceptor.java
+++ 
b/jdbc/src/java/org/apache/hive/jdbc/saml/HttpSamlAuthRequestInterceptor.java
@@ -64,9 +64,4 @@ public class HttpSamlAuthRequestInterceptor extends 
HttpRequestInterceptorBase {
       httpRequest.addHeader(HiveSamlUtils.SSO_TOKEN_RESPONSE_PORT, port);
     }
   }
-
-  @Override
-  protected String getAuthType() {
-    return "SAML";
-  }
 }
diff --git a/service/src/java/org/apache/hive/service/auth/AuthType.java 
b/service/src/java/org/apache/hive/service/auth/AuthType.java
index 104483049f2..db733d5f51c 100644
--- a/service/src/java/org/apache/hive/service/auth/AuthType.java
+++ b/service/src/java/org/apache/hive/service/auth/AuthType.java
@@ -138,13 +138,6 @@ public class AuthType {
     return "";
   }
 
-  public boolean isLoadedFirst(HiveAuthConstants.AuthTypes type) {
-    if (!isEnabled(type) || authTypes.isEmpty()) {
-      return false;
-    }
-    return authTypes.get(0) == type;
-  }
-
   public boolean isPasswordBasedAuth(HiveAuthConstants.AuthTypes type) {
     return PASSWORD_BASED_TYPES.contains(type);
   }
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 263ac3a6092..a7130bcc190 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
@@ -44,12 +44,12 @@ import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import com.google.common.io.ByteStreams;
 
+import org.apache.commons.lang3.StringUtils;
 import org.apache.hadoop.hive.conf.Constants;
 import org.apache.hadoop.hive.conf.HiveConf;
 import org.apache.hadoop.hive.conf.HiveConf.ConfVars;
 import org.apache.hadoop.hive.shims.HadoopShims.KerberosNameShim;
 import org.apache.hadoop.hive.shims.ShimLoader;
-import org.apache.hadoop.hive.shims.Utils;
 import org.apache.hadoop.security.UserGroupInformation;
 import org.apache.hive.service.CookieSigner;
 import org.apache.hive.service.auth.AuthType;
@@ -110,9 +110,8 @@ public class ThriftHttpServlet extends TServlet {
   private boolean isCookieSecure;
   private boolean isHttpOnlyCookie;
   private final HiveAuthFactory hiveAuthFactory;
-  private static final String HIVE_DELEGATION_TOKEN_HEADER =  
"X-Hive-Delegation-Token";
+  public 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,
@@ -722,7 +721,13 @@ public class ThriftHttpServlet extends TServlet {
 
   private String getAuthHeaderDecodedString(HttpServletRequest request) throws 
HttpAuthenticationException {
     String authHeaderBase64Str = getAuthHeader(request);
-    return new String(Base64.getDecoder().decode(authHeaderBase64Str), 
StandardCharsets.UTF_8);
+    try {
+      return new String(Base64.getDecoder().decode(authHeaderBase64Str), 
StandardCharsets.UTF_8);
+    } catch (IllegalArgumentException e) {
+      // Auth header content is not base64 encoded
+      throw new HttpAuthenticationException("Authorization header received " +
+        "from the client does not contain base64 encoded data", e);
+    }
   }
 
   /**
@@ -755,34 +760,36 @@ public class ThriftHttpServlet extends TServlet {
     return authHeaderBase64String;
   }
 
-  private boolean isAuthTypeEnabled(HttpServletRequest request,
+  @VisibleForTesting
+  public boolean isAuthTypeEnabled(HttpServletRequest request,
       HiveAuthConstants.AuthTypes authType) {
-    String authMethod = request.getHeader(AUTH_TYPE);
 
-    if (authType.getAuthName().equalsIgnoreCase(authMethod) && 
this.authType.isEnabled(authType) ||
-        "UIDPWD".equalsIgnoreCase(authMethod) && 
this.authType.isPasswordBasedAuth(authType)) {
-      // Request has already set the "auth" header
+    if (hasAuthScheme(request, HttpAuthUtils.BASIC) && 
this.authType.isPasswordBasedAuth(authType)
+        && this.authType.isEnabled(authType)) {
+      // The "Authorization: Basic" scheme indicates password-based 
authentication.
+      return true;
+    }
+    if (this.authType.isEnabled(HiveAuthConstants.AuthTypes.KERBEROS) &&
+       authType == HiveAuthConstants.AuthTypes.KERBEROS &&
+       
(StringUtils.isNotEmpty(request.getHeader(HIVE_DELEGATION_TOKEN_HEADER)) ||
+       hasAuthScheme(request, HttpAuthUtils.NEGOTIATE))) {
+      // Hive delegation token or "Authorization: Negotiate" scheme indicates 
Kerberos
+      // authentication.
+      return true;
+    }
+    if (this.authType.isEnabled(HiveAuthConstants.AuthTypes.SAML) &&
+        authType == HiveAuthConstants.AuthTypes.SAML &&
+        
(StringUtils.isNotEmpty(request.getHeader(HiveSamlUtils.SSO_TOKEN_RESPONSE_PORT))
 ||
+        hasAuthScheme(request, HttpAuthUtils.BEARER) && !hasJWT(request))) {
+      // X-Hive-Token-Response-Port header or "Authorization: Bearer <SAML 
TOKEN>" scheme
+      // indicates SAML authentication.
+      return true;
+    }
+    if (this.authType.isEnabled(HiveAuthConstants.AuthTypes.JWT) &&
+        authType == HiveAuthConstants.AuthTypes.JWT &&
+        hasAuthScheme(request, HttpAuthUtils.BEARER) && hasJWT(request)) {
+      // The "Authorization: Bearer <any.JWT.token>" scheme indicates JWT 
authentication.
       return true;
-    } else if (authMethod == null) {
-      // Kerberos -> JWT -> SAML -> Password(fall through if there is no match)
-      // If the auth header is missing, the request must come from the old 
running client.
-      // We support mixing JWT and SAML or LDAP auth methods in old client,
-      // the way to tell them is whether there is JWT token in request header.
-      if (this.authType.isEnabled(HiveAuthConstants.AuthTypes.JWT)) {
-        if (authType == HiveAuthConstants.AuthTypes.JWT) {
-          return hasJWT(request);
-        } else if (authType != HiveAuthConstants.AuthTypes.KERBEROS) {
-          // If you wish to try JWT,KERBEROS with the old client,
-          // append the property http.header.auth=kerberos to the URL.
-          return this.authType.isEnabled(authType);
-        }
-      }
-
-      if (this.authType.isLoadedFirst(authType)) {
-        // This is important to keep compatible with old clients, the first 
auth method
-        // takes over when the "auth" header is missing.
-        return true;
-      }
     }
     return false;
   }
@@ -799,6 +806,22 @@ public class ThriftHttpServlet extends TServlet {
     return jwt.length == 3;
   }
 
+  private boolean hasAuthScheme(HttpServletRequest request, String authScheme) 
{
+    String authHeader = request.getHeader(HttpAuthUtils.AUTHORIZATION);
+    if (authHeader == null || authHeader.isEmpty()) {
+      return false;
+    }
+
+    LOG.debug("HTTP Auth Header [{}]", authHeader);
+
+    String[] parts = authHeader.trim().split(" ");
+    if (parts.length < 2) {
+      return false;
+    }
+
+    return parts[0].equalsIgnoreCase(authScheme.toLowerCase());
+  }
+
   private static String getDoAsQueryParam(String queryString) {
     if (LOG.isDebugEnabled()) {
       LOG.debug("URL query string:" + queryString);
diff --git a/service/src/test/org/apache/hive/service/auth/TestAuthType.java 
b/service/src/test/org/apache/hive/service/auth/TestAuthType.java
index 09b0207972d..466f8d5c433 100644
--- a/service/src/test/org/apache/hive/service/auth/TestAuthType.java
+++ b/service/src/test/org/apache/hive/service/auth/TestAuthType.java
@@ -95,11 +95,6 @@ public class TestAuthType {
           HiveAuthConstants.AuthTypes authMech = 
EnumUtils.getEnumIgnoreCase(HiveAuthConstants.AuthTypes.class,
               authMethods[i]);
           Assert.assertTrue(authType.isEnabled(authMech));
-          if (i == 0) {
-            Assert.assertTrue(authType.isLoadedFirst(authMech));
-          } else {
-            Assert.assertFalse(authType.isLoadedFirst(authMech));
-          }
         }
       }
     } catch (Exception e) {

Reply via email to