Skip to content

World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.

[#1185] feat(server-common): Server supports Kerberos authentication (#1614)

qqqttt123173dd076da05
diff --git a/LICENSE b/LICENSE
index 8a2f2fac8a..63d790efff 100644
--- a/LICENSE
+++ b/LICENSE
@@ -253,6 +253,10 @@
Apache Hadoop
./dev/docker/hive/hadoop-env.sh
./dev/docker/hive/yarn-env.sh
+ ./common/src/main/java/com/datastrato/gravitino/auth/KerberosUtils.java
+ ./server-common/src/main/java/com/datastrato/gravitino/server/auth/KerberosAuthenticator.java
+ ./server-common/src/test/java/com/datastrato/gravitino/server/auth/KerberosTestUtils.java
+ ./server-common/src/main/java/com/datastrato/gravitino/server/auth/KerberosServerUtils.java
Apache Kafka
./core/src/main/java/com/datastrato/gravitino/utils/Bytes.java
diff --git a/LICENSE.bin b/LICENSE.bin
index 2cede6220f..6f91d9ce18 100644
--- a/LICENSE.bin
+++ b/LICENSE.bin
@@ -296,6 +296,7 @@
Apache Groovy
Apache Yetus
Apache Yetus - Audience Annotations
+ Apache Kerby
Jackson JSON processor
DataNucleus
Modernizer Maven Plugin
diff --git a/api/src/main/java/com/datastrato/gravitino/exceptions/UnauthorizedException.java b/api/src/main/java/com/datastrato/gravitino/exceptions/UnauthorizedException.java
index e5916e614e..47dc4b0312 100644
--- a/api/src/main/java/com/datastrato/gravitino/exceptions/UnauthorizedException.java
+++ b/api/src/main/java/com/datastrato/gravitino/exceptions/UnauthorizedException.java
@@ -5,9 +5,14 @@
package com.datastrato.gravitino.exceptions;
+import com.google.common.collect.Lists;
+import java.util.List;
+
/** Exception thrown when a user is not authorized to perform an action. */
public class UnauthorizedException extends GravitinoRuntimeException {
+ private final List<String> challenges = Lists.newArrayList();
+
public UnauthorizedException(String message) {
super(message);
}
@@ -15,4 +20,13 @@ public class UnauthorizedException extends GravitinoRuntimeException {
public UnauthorizedException(String message, Throwable cause) {
super(message, cause);
}
+
+ public UnauthorizedException(String message, String challenge) {
+ super(message);
+ challenges.add(challenge);
+ }
+
+ public List<String> getChallenges() {
+ return challenges;
+ }
}
diff --git a/bin/gravitino.sh b/bin/gravitino.sh
index 802bd589e2..34ca45e135 100755
--- a/bin/gravitino.sh
+++ b/bin/gravitino.sh
@@ -153,6 +153,7 @@ if [ "$JVM_VERSION" -eq 17 ]; then
JAVA_OPTS+=" --add-opens java.base/sun.nio.cs=ALL-UNNAMED"
JAVA_OPTS+=" --add-opens java.base/sun.security.action=ALL-UNNAMED"
JAVA_OPTS+=" --add-opens java.base/sun.util.calendar=ALL-UNNAMED"
+ JAVA_OPTS+=" --add-opens", "java.security.jgss/sun.security.krb5=ALL-UNNAMED"
fi
addJarInDir "${GRAVITINO_HOME}/libs"
diff --git a/build.gradle.kts b/build.gradle.kts
index 5f2bfcd27a..ea3cd0ab7e 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -78,7 +78,8 @@ project.extra["extraJvmArgs"] = if (extra["jdkVersion"] in listOf("8", "11")) {
"--add-opens", "java.base/sun.nio.ch=ALL-UNNAMED",
"--add-opens", "java.base/sun.nio.cs=ALL-UNNAMED",
"--add-opens", "java.base/sun.security.action=ALL-UNNAMED",
- "--add-opens", "java.base/sun.util.calendar=ALL-UNNAMED"
+ "--add-opens", "java.base/sun.util.calendar=ALL-UNNAMED",
+ "--add-opens", "java.security.jgss/sun.security.krb5=ALL-UNNAMED"
)
}
diff --git a/common/src/main/java/com/datastrato/gravitino/auth/AuthConstants.java b/common/src/main/java/com/datastrato/gravitino/auth/AuthConstants.java
index bda20c47aa..a5bf7f0185 100644
--- a/common/src/main/java/com/datastrato/gravitino/auth/AuthConstants.java
+++ b/common/src/main/java/com/datastrato/gravitino/auth/AuthConstants.java
@@ -12,6 +12,11 @@ public interface AuthConstants {
String AUTHORIZATION_BASIC_HEADER = "Basic ";
+ String NEGOTIATE = "Negotiate";
+ String AUTHORIZATION_NEGOTIATE_HEADER = NEGOTIATE + " ";
+
+ String HTTP_CHALLENGE_HEADER = "WWW-Authenticate";
+
String ANONYMOUS_USER = "anonymous";
// Refer to the style of `AuthenticationFilter#AuthenticatedRoleAttributeName` of Apache Pulsar
diff --git a/common/src/main/java/com/datastrato/gravitino/auth/AuthenticatorType.java b/common/src/main/java/com/datastrato/gravitino/auth/AuthenticatorType.java
index d83ce9ba3c..90a454a22e 100644
--- a/common/src/main/java/com/datastrato/gravitino/auth/AuthenticatorType.java
+++ b/common/src/main/java/com/datastrato/gravitino/auth/AuthenticatorType.java
@@ -8,5 +8,6 @@ package com.datastrato.gravitino.auth;
public enum AuthenticatorType {
NONE,
SIMPLE,
- OAUTH
+ OAUTH,
+ KERBEROS
}
diff --git a/common/src/main/java/com/datastrato/gravitino/auth/KerberosUtils.java b/common/src/main/java/com/datastrato/gravitino/auth/KerberosUtils.java
new file mode 100644
index 0000000000..7a50160a87
--- /dev/null
+++ b/common/src/main/java/com/datastrato/gravitino/auth/KerberosUtils.java
@@ -0,0 +1,126 @@
+/**
+ * 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
+ *
+ * <p>http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * <p>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 com.datastrato.gravitino.auth;
+
+import java.security.Principal;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import javax.security.auth.Subject;
+import javax.security.auth.kerberos.KerberosPrincipal;
+import javax.security.auth.login.AppConfigurationEntry;
+import javax.security.auth.login.Configuration;
+import javax.security.auth.login.LoginContext;
+import javax.security.auth.login.LoginException;
+import org.ietf.jgss.GSSException;
+import org.ietf.jgss.Oid;
+
+// Referred from Apache Hadoop KerberosTestUtils.java
+// Remove the part methods
+// Remove the support the IBM JDK
+// Split method `doAs` into two methods
+// hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/\
+// authentication/KerberosTestUtils.java
+public class KerberosUtils {
+
+ private KerberosUtils() {}
+
+ public static final Oid GSS_SPNEGO_MECH_OID = getNumericOidInstance("1.3.6.1.5.5.2");
+ public static final Oid GSS_KRB5_MECH_OID = getNumericOidInstance("1.2.840.113554.1.2.2");
+ public static final Oid NT_GSS_KRB5_PRINCIPAL_OID =
+ getNumericOidInstance("1.2.840.113554.1.2.2.1");
+
+ // Numeric oids will never generate a GSSException for a malformed oid.
+ // Use to initialize statics.
+ private static Oid getNumericOidInstance(String oidName) {
+ try {
+ return new Oid(oidName);
+ } catch (GSSException ex) {
+ throw new IllegalArgumentException(ex);
+ }
+ }
+
+ public static LoginContext login(String principal, String keyTabFile) throws LoginException {
+ LoginContext loginContext = null;
+ Set<Principal> principals = new HashSet<>();
+ principals.add(new KerberosPrincipal(principal));
+ Subject subject = new Subject(false, principals, new HashSet<>(), new HashSet<>());
+ loginContext =
+ new LoginContext("", subject, null, new KerberosConfiguration(principal, keyTabFile));
+ loginContext.login();
+ return loginContext;
+ }
+
+ public static <T> T doAs(Subject subject, final Callable<T> callable) throws Exception {
+ try {
+ return Subject.doAs(
+ subject,
+ new PrivilegedExceptionAction<T>() {
+ @Override
+ public T run() throws Exception {
+ return callable.call();
+ }
+ });
+ } catch (PrivilegedActionException ex) {
+ throw ex.getException();
+ }
+ }
+
+ private static class KerberosConfiguration extends Configuration {
+ private final String principal;
+ private final String keyTabFile;
+
+ public KerberosConfiguration(String principal, String keyTabFile) {
+ this.principal = principal;
+ this.keyTabFile = keyTabFile;
+ }
+
+ @Override
+ public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
+ Map<String, String> options = new HashMap<String, String>();
+
+ options.put("keyTab", keyTabFile);
+ options.put("principal", principal);
+ options.put("useKeyTab", "true");
+ options.put("storeKey", "true");
+ options.put("doNotPrompt", "true");
+ options.put("useTicketCache", "true");
+ options.put("renewTGT", "true");
+ options.put("refreshKrb5Config", "true");
+ options.put("isInitiator", "true");
+ String ticketCache = System.getenv("KRB5CCNAME");
+ if (ticketCache != null) {
+ options.put("ticketCache", ticketCache);
+ }
+ options.put("debug", "true");
+
+ return new AppConfigurationEntry[] {
+ new AppConfigurationEntry(
+ getKrb5LoginModuleName(),
+ AppConfigurationEntry.LoginModuleControlFlag.REQUIRED,
+ options),
+ };
+ }
+ }
+
+ /* Return the Kerberos login module name */
+ public static String getKrb5LoginModuleName() {
+ return "com.sun.security.auth.module.Krb5LoginModule";
+ }
+}
diff --git a/docs/open-api/openapi.yaml b/docs/open-api/openapi.yaml
index 0eb3342b4f..1ebebfd467 100644
--- a/docs/open-api/openapi.yaml
+++ b/docs/open-api/openapi.yaml
@@ -255,3 +255,7 @@ components:
type: http
scheme: basic
+ KerberosAuth:
+ type: http
+ scheme: negotiate
+
diff --git a/docs/security.md b/docs/security.md
index 55b19111a9..8c47598638 100644
--- a/docs/security.md
+++ b/docs/security.md
@@ -53,15 +53,17 @@ GravitinoClient client = GravitinoClient.builder(uri)
### Server configuration
-| Configuration item | Description | Default value | Required | Since version |
-|---------------------------------------------------|-----------------------------------------------------------------------------|-------------------|-----------------------------------------|---------------|
-| `gravitino.authenticator` | The authenticator which Gravitino uses, setting as `simple` or `oauth`. | `simple` | No | 0.3.0 |
-| `gravitino.authenticator.oauth.serviceAudience` | The audience name when Gravitino uses OAuth as the authenticator. | `GravitinoServer` | No | 0.3.0 |
-| `gravitino.authenticator.oauth.allowSkewSecs` | The JWT allows skew seconds when Gravitino uses OAuth as the authenticator. | `0` | No | 0.3.0 |
-| `gravitino.authenticator.oauth.defaultSignKey` | The signing key of JWT when Gravitino uses OAuth as the authenticator. | (none) | Yes if use `oauth` as the authenticator | 0.3.0 |
-| `gravitino.authenticator.oauth.signAlgorithmType` | The signature algorithm when Gravitino uses OAuth as the authenticator. | `RS256` | No | 0.3.0 |
-| `gravitino.authenticator.oauth.serverUri` | The URI of the default OAuth server. | (none) | Yes if use `oauth` as the authenticator | 0.3.0 |
-| `gravitino.authenticator.oauth.tokenPath` | The path for token of the default OAuth server. | (none) | Yes if use `oauth` as the authenticator | 0.3.0 |
+| Configuration item | Description | Default value | Required | Since version |
+|---------------------------------------------------|------------------------------------------------------------------------------------|-------------------|--------------------------------------------|---------------|
+| `gravitino.authenticator` | The authenticator which Gravitino uses, setting as `simple`,`oauth` or `kerberos`. | `simple` | No | 0.3.0 |
+| `gravitino.authenticator.oauth.serviceAudience` | The audience name when Gravitino uses OAuth as the authenticator. | `GravitinoServer` | No | 0.3.0 |
+| `gravitino.authenticator.oauth.allowSkewSecs` | The JWT allows skew seconds when Gravitino uses OAuth as the authenticator. | `0` | No | 0.3.0 |
+| `gravitino.authenticator.oauth.defaultSignKey` | The signing key of JWT when Gravitino uses OAuth as the authenticator. | (none) | Yes if use `oauth` as the authenticator | 0.3.0 |
+| `gravitino.authenticator.oauth.signAlgorithmType` | The signature algorithm when Gravitino uses OAuth as the authenticator. | `RS256` | No | 0.3.0 |
+| `gravitino.authenticator.oauth.serverUri` | The URI of the default OAuth server. | (none) | Yes if use `oauth` as the authenticator | 0.3.0 |
+| `gravitino.authenticator.oauth.tokenPath` | The path for token of the default OAuth server. | (none) | Yes if use `oauth` as the authenticator | 0.3.0 |
+| `gravitino.authenticator.kerberos.principal` | Indicates the Kerberos principal to be used for HTTP endpoint. | (none) | Yes if use `kerberos` as the authenticator | 0.4.0 |
+| `gravitino.authenticator.kerberos.keytab` | Location of the keytab file with the credentials for the principal. | (none) | Yes if use `kerberos` as the authenticator | 0.4.0 |
The signature algorithms that Gravitino supports follows:
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index 986001b3dc..43ddf61527 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -17,6 +17,7 @@ airlift-units = "1.8"
airlift-log = "231"
hive2 = "2.3.9"
hadoop2 = "2.10.2"
+hadoop-minikdc = "3.3.6"
httpclient5 = "5.2.1"
mockserver = "5.15.0"
commons-lang3 = "3.14.0"
@@ -49,6 +50,7 @@ gradle-extensions-plugin = '1.74'
publish-plugin = '1.2.0'
rat-plugin = '0.8.0'
shadow-plugin = "8.1.1"
+kerby = "2.0.3"
node-plugin = "7.0.1"
commons-cli = "1.2"
@@ -60,6 +62,8 @@ jackson-annotations = { group = "com.fasterxml.jackson.core", name = "jackson-an
jackson-datatype-jdk8 = { group = "com.fasterxml.jackson.datatype", name = "jackson-datatype-jdk8", version.ref = "jackson" }
jackson-datatype-jsr310 = { group = "com.fasterxml.jackson.datatype", name = "jackson-datatype-jsr310", version.ref = "jackson" }
guava = { group = "com.google.guava", name = "guava", version.ref = "guava" }
+kerby-core = { group = "org.apache.kerby", name = "kerb-core", version.ref = "kerby"}
+kerby-simplekdc = { group = "org.apache.kerby", name = "kerb-simplekdc", version.ref = "kerby"}
lombok = { group = "org.projectlombok", name = "lombok", version.ref = "lombok" }
junit-jupiter-api = { group = "org.junit.jupiter", name = "junit-jupiter-api", version.ref = "junit" }
junit-jupiter-params = { group = "org.junit.jupiter", name = "junit-jupiter-params", version.ref = "junit" }
@@ -135,6 +139,7 @@ prometheus-servlet = { group = "io.prometheus", name = "simpleclient_servlet", v
jsqlparser = { group = "com.github.jsqlparser", name = "jsqlparser", version.ref = "jsqlparser" }
mysql-driver = { group = "mysql", name = "mysql-connector-java", version.ref = "mysql" }
postgresql-driver = { group = "org.postgresql", name = "postgresql", version.ref = "postgresql" }
+minikdc = { group = "org.apache.hadoop", name = "hadoop-minikdc", version.ref = "hadoop-minikdc"}
immutables-value = { module = "org.immutables:value", version.ref = "immutables-value" }
commons-cli = { group = "commons-cli", name = "commons-cli", version.ref = "commons-cli" }
@@ -146,6 +151,7 @@ iceberg = ["iceberg-core", "iceberg-api"]
jwt = ["jwt-api", "jwt-impl", "jwt-gson"]
metrics = ["metrics-core", "metrics-jersey2", "metrics-jvm", "metrics-jmx", "metrics-servlets"]
prometheus = ["prometheus-servlet", "prometheus-dropwizard", "prometheus-client"]
+kerby = ["kerby-core", "kerby-simplekdc"]
[plugins]
protobuf = { id = "com.google.protobuf", version.ref = "protobuf-plugin" }
diff --git a/server-common/build.gradle.kts b/server-common/build.gradle.kts
index 5e4632fe2f..bd60703cad 100644
--- a/server-common/build.gradle.kts
+++ b/server-common/build.gradle.kts
@@ -24,6 +24,7 @@ dependencies {
implementation(libs.bundles.jetty)
implementation(libs.bundles.jwt)
implementation(libs.bundles.metrics)
+ implementation(libs.bundles.kerby)
implementation(libs.prometheus.servlet)
testImplementation(libs.junit.jupiter.api)
@@ -31,4 +32,7 @@ dependencies {
testRuntimeOnly(libs.junit.jupiter.engine)
testImplementation(libs.mockito.core)
testImplementation(libs.commons.io)
+ testImplementation(libs.minikdc) {
+ exclude("org.apache.directory.api", "api-ldap-schema-data")
+ }
}
diff --git a/server-common/src/main/java/com/datastrato/gravitino/server/auth/AuthenticationFilter.java b/server-common/src/main/java/com/datastrato/gravitino/server/auth/AuthenticationFilter.java
index c2498fed7a..5c4cb6b9ce 100644
--- a/server-common/src/main/java/com/datastrato/gravitino/server/auth/AuthenticationFilter.java
+++ b/server-common/src/main/java/com/datastrato/gravitino/server/auth/AuthenticationFilter.java
@@ -59,6 +59,14 @@ public class AuthenticationFilter implements Filter {
chain.doFilter(request, response);
} catch (UnauthorizedException ue) {
HttpServletResponse resp = (HttpServletResponse) response;
+ if (!ue.getChallenges().isEmpty()) {
+ // For some authentication, HTTP response can provide some challenge information
+ // to let client to create correct authenticated request.
+ // Refer to https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/WWW-Authenticate
+ for (String challenge : ue.getChallenges()) {
+ resp.setHeader(AuthConstants.HTTP_CHALLENGE_HEADER, challenge);
+ }
+ }
resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, ue.getMessage());
}
}
diff --git a/server-common/src/main/java/com/datastrato/gravitino/server/auth/AuthenticatorFactory.java b/server-common/src/main/java/com/datastrato/gravitino/server/auth/AuthenticatorFactory.java
index 5623919136..8b4a677d9d 100644
--- a/server-common/src/main/java/com/datastrato/gravitino/server/auth/AuthenticatorFactory.java
+++ b/server-common/src/main/java/com/datastrato/gravitino/server/auth/AuthenticatorFactory.java
@@ -22,7 +22,9 @@ public class AuthenticatorFactory {
AuthenticatorType.SIMPLE.name().toLowerCase(),
SimpleAuthenticator.class.getCanonicalName(),
AuthenticatorType.OAUTH.name().toLowerCase(),
- OAuth2TokenAuthenticator.class.getCanonicalName());
+ OAuth2TokenAuthenticator.class.getCanonicalName(),
+ AuthenticatorType.KERBEROS.name().toLowerCase(),
+ KerberosAuthenticator.class.getCanonicalName());
private AuthenticatorFactory() {}
diff --git a/server-common/src/main/java/com/datastrato/gravitino/server/auth/KerberosAuthenticator.java b/server-common/src/main/java/com/datastrato/gravitino/server/auth/KerberosAuthenticator.java
new file mode 100644
index 0000000000..d9fd9f2711
--- /dev/null
+++ b/server-common/src/main/java/com/datastrato/gravitino/server/auth/KerberosAuthenticator.java
@@ -0,0 +1,183 @@
+/**
+ * Licensed 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
+ *
+ * <p>http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * <p>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. See accompanying LICENSE file.
+ */
+package com.datastrato.gravitino.server.auth;
+
+import com.datastrato.gravitino.Config;
+import com.datastrato.gravitino.UserPrincipal;
+import com.datastrato.gravitino.auth.AuthConstants;
+import com.datastrato.gravitino.auth.KerberosUtils;
+import com.datastrato.gravitino.exceptions.UnauthorizedException;
+import java.io.File;
+import java.security.Principal;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.util.Base64;
+import javax.security.auth.Subject;
+import javax.security.auth.kerberos.KerberosPrincipal;
+import javax.security.auth.kerberos.KeyTab;
+import org.apache.commons.lang3.StringUtils;
+import org.ietf.jgss.GSSContext;
+import org.ietf.jgss.GSSCredential;
+import org.ietf.jgss.GSSException;
+import org.ietf.jgss.GSSManager;
+import org.ietf.jgss.Oid;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+/**
+ * Provides Kerberos authentication mechanism. Referred from Apache Hadoop
+ * KerberosAuthenticationHandler.java
+ *
+ * <p>KerberosAuthenticator doesn't support to use * as principal.
+ *
+ * <p>hadoop-common-project/hadoop-auth/src/main/java/org/apache/hadoop/\
+ * security/authentication/server/KerberosAuthenticationHandler.java
+ */
+public class KerberosAuthenticator implements Authenticator {
+
+ public static final Logger LOG = LoggerFactory.getLogger(KerberosAuthenticator.class);
+ private final Subject serverSubject = new Subject();
+ private GSSManager gssManager;
+
+ @Override
+ public void initialize(Config config) throws RuntimeException {
+ try {
+ String principal = config.get(KerberosConfig.PRINCIPAL);
+ String keytab = config.get(KerberosConfig.KEYTAB);
+ File keytabFile = new File(keytab);
+ if (!keytabFile.exists()) {
+ throw new IllegalArgumentException(String.format("Keytab %s doesn't exist", keytab));
+ }
+
+ if (!keytabFile.canRead()) {
+ throw new IllegalArgumentException(String.format("Keytab %s can't be read", keytab));
+ }
+
+ Principal krbPrincipal = new KerberosPrincipal(principal);
+ LOG.info("Using keytab {}, for principal {}", keytab, krbPrincipal);
+ serverSubject.getPrincipals().add(krbPrincipal);
+ KeyTab keytabInstance = KeyTab.getInstance(keytabFile);
+ serverSubject.getPrivateCredentials().add(keytabInstance);
+
+ gssManager =
+ Subject.doAs(
+ serverSubject,
+ new PrivilegedExceptionAction<GSSManager>() {
+ @Override
+ public GSSManager run() throws Exception {
+ return GSSManager.getInstance();
+ }
+ });
+ } catch (PrivilegedActionException ex) {
+ throw new RuntimeException(ex);
+ }
+ }
+
+ @Override
+ public boolean isDataFromToken() {
+ return true;
+ }
+
+ @Override
+ public Principal authenticateToken(byte[] tokenData) {
+ if (tokenData == null) {
+ throw new UnauthorizedException("Empty token authorization header", AuthConstants.NEGOTIATE);
+ }
+
+ String authData = new String(tokenData);
+ if (StringUtils.isBlank(authData)
+ || !authData.startsWith(AuthConstants.AUTHORIZATION_NEGOTIATE_HEADER)) {
+ throw new UnauthorizedException(
+ "Invalid token authorization header", AuthConstants.NEGOTIATE);
+ }
+
+ String token = authData.substring(AuthConstants.AUTHORIZATION_NEGOTIATE_HEADER.length());
+ byte[] clientToken = Base64.getDecoder().decode(token);
+ if (StringUtils.isBlank(token)) {
+ throw new UnauthorizedException("Blank token found", AuthConstants.NEGOTIATE);
+ }
+
+ try {
+ String serverPrincipal = KerberosServerUtils.getTokenServerName(clientToken);
+ return Subject.doAs(
+ serverSubject,
+ new PrivilegedExceptionAction<Principal>() {
+ @Override
+ public Principal run() throws Exception {
+ return retrievePrincipalFromToken(serverPrincipal, clientToken);
+ }
+ });
+ } catch (Exception e) {
+ throw new UnauthorizedException("Fail to validate the token", AuthConstants.NEGOTIATE);
+ }
+ }
+
+ private Principal retrievePrincipalFromToken(String serverPrincipal, byte[] clientToken)
+ throws GSSException {
+ GSSContext gssContext = null;
+ GSSCredential gssCreds = null;
+ try {
+ LOG.trace("SPNEGO initiated with server principal [{}]", serverPrincipal);
+
+ gssCreds =
+ this.gssManager.createCredential(
+ this.gssManager.createName(serverPrincipal, KerberosUtils.NT_GSS_KRB5_PRINCIPAL_OID),
+ GSSCredential.INDEFINITE_LIFETIME,
+ new Oid[] {KerberosUtils.GSS_SPNEGO_MECH_OID, KerberosUtils.GSS_KRB5_MECH_OID},
+ GSSCredential.ACCEPT_ONLY);
+
+ gssContext = this.gssManager.createContext(gssCreds);
+ byte[] serverToken = gssContext.acceptSecContext(clientToken, 0, clientToken.length);
+
+ String authenticateToken = null;
+ if (serverToken != null && serverToken.length > 0) {
+ authenticateToken = Base64.getEncoder().encodeToString(serverToken);
+ }
+
+ if (!gssContext.isEstablished()) {
+ LOG.trace("SPNEGO in progress");
+ String challenge = AuthConstants.AUTHORIZATION_NEGOTIATE_HEADER + authenticateToken;
+ throw new UnauthorizedException("GssContext isn't established", challenge);
+ }
+
+ // Usually principal names are in the form 'user/instance@REALM' or 'user@REALM'.
+ String[] principalComponents = gssContext.getSrcName().toString().split("@");
+ if (principalComponents.length != 2) {
+ throw new UnauthorizedException("Principal has wrong format", AuthConstants.NEGOTIATE);
+ }
+
+ String[] userAndInstance = principalComponents[0].split("/");
+ if (userAndInstance.length > 2) {
+ throw new UnauthorizedException("Principal has wrong format", AuthConstants.NEGOTIATE);
+ }
+
+ String user = userAndInstance[0];
+ // TODO: We will have KerberosUserPrincipal in the future.
+ // We can put more information of Kerberos to the KerberosUserPrincipal
+ // For example, we can put the token into the KerberosUserPrincipal,
+ // We can return the token to the client in the AuthenticationFilter. It will be convenient
+ // for client to establish the security context. Hadoop uses the cookie to store the token.
+ // For now, we don't store it in the cookie. I can have a simple implementation. first.
+ // It's also not required for the protocol.
+ // https://datatracker.ietf.org/doc/html/rfc4559
+ return new UserPrincipal(user);
+ } finally {
+ if (gssContext != null) {
+ gssContext.dispose();
+ }
+
+ if (gssCreds != null) {
+ gssCreds.dispose();
+ }
+ }
+ }
+}
diff --git a/server-common/src/main/java/com/datastrato/gravitino/server/auth/KerberosConfig.java b/server-common/src/main/java/com/datastrato/gravitino/server/auth/KerberosConfig.java
new file mode 100644
index 0000000000..3aa5315888
--- /dev/null
+++ b/server-common/src/main/java/com/datastrato/gravitino/server/auth/KerberosConfig.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.server.auth;
+
+import com.datastrato.gravitino.Configs;
+import com.datastrato.gravitino.config.ConfigBuilder;
+import com.datastrato.gravitino.config.ConfigConstants;
+import com.datastrato.gravitino.config.ConfigEntry;
+import org.apache.commons.lang3.StringUtils;
+
+public interface KerberosConfig extends Configs {
+
+ String KERBEROS_CONFIG_PREFIX = "gravitino.authenticator.kerberos.";
+
+ ConfigEntry<String> PRINCIPAL =
+ new ConfigBuilder(KERBEROS_CONFIG_PREFIX + "principal")
+ .doc("Indicates the Kerberos principal to be used for HTTP endpoint")
+ .version("0.4.0")
+ .stringConf()
+ .checkValue(StringUtils::isNotBlank, ConfigConstants.NOT_BLANK_ERROR_MSG)
+ .create();
+
+ ConfigEntry<String> KEYTAB =
+ new ConfigBuilder(KERBEROS_CONFIG_PREFIX + "keytab")
+ .doc("Location of the keytab file with the credentials for the principal")
+ .version("0.4.0")
+ .stringConf()
+ .checkValue(StringUtils::isNotBlank, ConfigConstants.NOT_BLANK_ERROR_MSG)
+ .create();
+}
diff --git a/server-common/src/main/java/com/datastrato/gravitino/server/auth/KerberosServerUtils.java b/server-common/src/main/java/com/datastrato/gravitino/server/auth/KerberosServerUtils.java
new file mode 100644
index 0000000000..75742c6fb6
--- /dev/null
+++ b/server-common/src/main/java/com/datastrato/gravitino/server/auth/KerberosServerUtils.java
@@ -0,0 +1,396 @@
+/**
+ * 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
+ *
+ * <p>http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * <p>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 com.datastrato.gravitino.server.auth;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.lang.reflect.InvocationTargetException;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.nio.ByteBuffer;
+import java.nio.charset.IllegalCharsetNameException;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Locale;
+import java.util.NoSuchElementException;
+import java.util.Set;
+import java.util.regex.Pattern;
+import javax.security.auth.Subject;
+import javax.security.auth.kerberos.KerberosPrincipal;
+import javax.security.auth.kerberos.KerberosTicket;
+import javax.security.auth.kerberos.KeyTab;
+import org.apache.kerby.kerberos.kerb.keytab.Keytab;
+import org.apache.kerby.kerberos.kerb.type.base.PrincipalName;
+import org.ietf.jgss.GSSException;
+import org.ietf.jgss.Oid;
+
+// Referred from Apache Hadoop KerberosUtil.java
+// Remove part methods
+// hadoop-common-project/hadoop-auth/src/main/java/org/apache/hadoop/\
+// security/authentication/util/KerberosUtil.java
+public class KerberosServerUtils {
+
+ /**
+ * Return the default realm for this JVM.
+ *
+ * @return The default realm
+ * @throws IllegalArgumentException If the default realm does not exist.
+ * @throws ClassNotFoundException Not thrown. Exists for compatibility.
+ * @throws NoSuchMethodException Not thrown. Exists for compatibility.
+ * @throws IllegalAccessException Not thrown. Exists for compatibility.
+ * @throws InvocationTargetException Not thrown. Exists for compatibility.
+ */
+ public static String getDefaultRealm()
+ throws ClassNotFoundException, NoSuchMethodException, IllegalArgumentException,
+ IllegalAccessException, InvocationTargetException {
+ // Any name is okay.
+ return new KerberosPrincipal("tmp", 1).getRealm();
+ }
+
+ /**
+ * Return the default realm for this JVM. If the default realm does not exist, this method returns
+ * null.
+ *
+ * @return The default realm
+ */
+ public static String getDefaultRealmProtected() {
+ try {
+ return getDefaultRealm();
+ } catch (Exception e) {
+ // silently catch everything
+ return null;
+ }
+ }
+
+ /*
+ * For a Service Host Principal specification, map the host's domain
+ * to kerberos realm, as specified by krb5.conf [domain_realm] mappings.
+ * Unfortunately the mapping routines are private to the security.krb5
+ * package, so have to construct a PrincipalName instance to derive the realm.
+ *
+ * Many things can go wrong with Kerberos configuration, and this is not
+ * the place to be throwing exceptions to help debug them. Nor do we choose
+ * to make potentially voluminous logs on every call to a communications API.
+ * So we simply swallow all exceptions from the underlying libraries and
+ * return null if we can't get a good value for the realmString.
+ *
+ * @param shortprinc A service principal name with host fqdn as instance, e.g.
+ * "HTTP/myhost.mydomain"
+ * @return String value of Kerberos realm, mapped from host fqdn
+ * May be default realm, or may be null.
+ */
+ public static String getDomainRealm(String shortprinc) {
+ Class<?> classRef;
+ Object principalName; // of type sun.security.krb5.PrincipalName or IBM equiv
+ String realmString = null;
+ try {
+ classRef = Class.forName("sun.security.krb5.PrincipalName");
+ int tKrbNtSrvHst = classRef.getField("KRB_NT_SRV_HST").getInt(null);
+ principalName =
+ classRef.getConstructor(String.class, int.class).newInstance(shortprinc, tKrbNtSrvHst);
+ realmString =
+ (String)
+ classRef
+ .getMethod("getRealmString", new Class[0])
+ .invoke(principalName, new Object[0]);
+ } catch (RuntimeException rte) {
+ // silently catch everything
+ } catch (Exception e) {
+ // silently return default realm (which may itself be null)
+ }
+ if (null == realmString || realmString.equals("")) {
+ return getDefaultRealmProtected();
+ } else {
+ return realmString;
+ }
+ }
+
+ /* Return fqdn of the current host */
+ public static String getLocalHostName() throws UnknownHostException {
+ return InetAddress.getLocalHost().getCanonicalHostName();
+ }
+
+ /**
+ * Create Kerberos principal for a given service and hostname, inferring realm from the fqdn of
+ * the hostname. It converts hostname to lower case. If hostname is null or "0.0.0.0", it uses
+ * dynamically looked-up fqdn of the current host instead. If domain_realm mappings are
+ * inadequately specified, it will use default_realm, per usual Kerberos behavior. If
+ * default_realm also gives a null value, then a principal without realm will be returned, which
+ * by Kerberos definitions is just another way to specify default realm.
+ *
+ * @param service Service for which you want to generate the principal.
+ * @param hostname Fully-qualified domain name.
+ * @return Converted Kerberos principal name.
+ * @throws UnknownHostException If no IP address for the local host could be found.
+ */
+ public static final String getServicePrincipal(String service, String hostname)
+ throws UnknownHostException {
+ String fqdn = hostname;
+ String shortprinc = null;
+ String realmString = null;
+ if (null == fqdn || fqdn.equals("") || fqdn.equals("0.0.0.0")) {
+ fqdn = getLocalHostName();
+ }
+ // convert hostname to lowercase as kerberos does not work with hostnames
+ // with uppercase characters.
+ fqdn = fqdn.toLowerCase(Locale.US);
+ shortprinc = service + "/" + fqdn;
+ // Obtain the realm name inferred from the domain of the host
+ realmString = getDomainRealm(shortprinc);
+ if (null == realmString || realmString.equals("")) {
+ return shortprinc;
+ } else {
+ return shortprinc + "@" + realmString;
+ }
+ }
+
+ /**
+ * Get all the unique principals present in the keytabfile.
+ *
+ * @param keytabFileName Name of the keytab file to be read.
+ * @return list of unique principals in the keytab.
+ * @throws IOException If keytab entries cannot be read from the file.
+ */
+ static final String[] getPrincipalNames(String keytabFileName) throws IOException {
+ Keytab keytab = Keytab.loadKeytab(new File(keytabFileName));
+ Set<String> principals = new HashSet<>();
+ List<PrincipalName> entries = keytab.getPrincipals();
+ for (PrincipalName entry : entries) {
+ principals.add(entry.getName().replace("\\", "/"));
+ }
+ return principals.toArray(new String[0]);
+ }
+
+ /**
+ * Get all the unique principals from keytabfile which matches a pattern.
+ *
+ * @param keytab Name of the keytab file to be read.
+ * @param pattern pattern to be matched.
+ * @return list of unique principals which matches the pattern.
+ * @throws IOException if cannot get the principal name
+ */
+ public static final String[] getPrincipalNames(String keytab, Pattern pattern)
+ throws IOException {
+ String[] principals = getPrincipalNames(keytab);
+ if (principals.length != 0) {
+ List<String> matchingPrincipals = new ArrayList<String>();
+ for (String principal : principals) {
+ if (pattern.matcher(principal).matches()) {
+ matchingPrincipals.add(principal);
+ }
+ }
+ principals = matchingPrincipals.toArray(new String[0]);
+ }
+ return principals;
+ }
+
+ /**
+ * Check if the subject contains Kerberos keytab related objects. The Kerberos keytab object
+ * attached in subject has been changed from KerberosKey (JDK 7) to KeyTab (JDK 8)
+ *
+ * @param subject subject to be checked
+ * @return true if the subject contains Kerberos keytab
+ */
+ public static boolean hasKerberosKeyTab(Subject subject) {
+ return !subject.getPrivateCredentials(KeyTab.class).isEmpty();
+ }
+
+ /**
+ * Check if the subject contains Kerberos ticket.
+ *
+ * @param subject subject to be checked
+ * @return true if the subject contains Kerberos ticket
+ */
+ public static boolean hasKerberosTicket(Subject subject) {
+ return !subject.getPrivateCredentials(KerberosTicket.class).isEmpty();
+ }
+
+ /**
+ * Extract the TGS server principal from the given gssapi kerberos or spnego wrapped token.
+ *
+ * @param rawToken bytes of the gss token
+ * @return String of server principal
+ * @throws IllegalArgumentException if token is undecodable
+ */
+ public static String getTokenServerName(byte[] rawToken) {
+ // subsequent comments include only relevant portions of the kerberos
+ // DER encoding that will be extracted.
+ DER token = new DER(rawToken);
+ // InitialContextToken ::= [APPLICATION 0] IMPLICIT SEQUENCE {
+ // mech OID
+ // mech-token (NegotiationToken or InnerContextToken)
+ // }
+ DER oid = token.next();
+ if (oid.equals(DER.SPNEGO_MECH_OID)) {
+ // NegotiationToken ::= CHOICE {
+ // neg-token-init[0] NegTokenInit
+ // }
+ // NegTokenInit ::= SEQUENCE {
+ // mech-token[2] InitialContextToken
+ // }
+ token = token.next().get(0xa0, 0x30, 0xa2, 0x04).next();
+ oid = token.next();
+ }
+ if (!oid.equals(DER.KRB5_MECH_OID)) {
+ throw new IllegalArgumentException("Malformed gss token");
+ }
+ // InnerContextToken ::= {
+ // token-id[1]
+ // AP-REQ
+ // }
+ if (token.next().getTag() != 1) {
+ throw new IllegalArgumentException("Not an AP-REQ token");
+ }
+ // AP-REQ ::= [APPLICATION 14] SEQUENCE {
+ // ticket[3] Ticket
+ // }
+ DER ticket = token.next().get(0x6e, 0x30, 0xa3, 0x61, 0x30);
+ // Ticket ::= [APPLICATION 1] SEQUENCE {
+ // realm[1] String
+ // sname[2] PrincipalName
+ // }
+ // PrincipalName ::= SEQUENCE {
+ // name-string[1] SEQUENCE OF String
+ // }
+ String realm = ticket.get(0xa1, 0x1b).getAsString();
+ DER names = ticket.get(0xa2, 0x30, 0xa1, 0x30);
+ StringBuilder sb = new StringBuilder();
+ while (names.hasNext()) {
+ if (sb.length() > 0) {
+ sb.append('/');
+ }
+ sb.append(names.next().getAsString());
+ }
+ return sb.append('@').append(realm).toString();
+ }
+
+ // basic ASN.1 DER decoder to traverse encoded byte arrays.
+ private static class DER implements Iterator<DER> {
+ static final DER SPNEGO_MECH_OID =
+ getDER(com.datastrato.gravitino.auth.KerberosUtils.GSS_SPNEGO_MECH_OID);
+ static final DER KRB5_MECH_OID =
+ getDER(com.datastrato.gravitino.auth.KerberosUtils.GSS_KRB5_MECH_OID);
+
+ private static DER getDER(Oid oid) {
+ try {
+ return new DER(oid.getDER());
+ } catch (GSSException ex) {
+ // won't happen. a proper OID is encodable.
+ throw new IllegalArgumentException(ex);
+ }
+ }
+
+ private final int tag;
+ private final ByteBuffer bb;
+
+ DER(byte[] buf) {
+ this(ByteBuffer.wrap(buf));
+ }
+
+ DER(ByteBuffer srcbb) {
+ tag = srcbb.get() & 0xff;
+ int length = readLength(srcbb);
+ bb = srcbb.slice();
+ bb.limit(length);
+ srcbb.position(srcbb.position() + length);
+ }
+
+ int getTag() {
+ return tag;
+ }
+
+ // standard ASN.1 encoding.
+ private static int readLength(ByteBuffer bb) {
+ int length = bb.get();
+ if ((length & (byte) 0x80) != 0) {
+ int varlength = length & 0x7f;
+ length = 0;
+ for (int i = 0; i < varlength; i++) {
+ length = (length << 8) | (bb.get() & 0xff);
+ }
+ }
+ return length;
+ }
+
+ DER choose(int subtag) {
+ while (hasNext()) {
+ DER der = next();
+ if (der.getTag() == subtag) {
+ return der;
+ }
+ }
+ return null;
+ }
+
+ DER get(int... tags) {
+ DER der = this;
+ for (int i = 0; i < tags.length; i++) {
+ int expectedTag = tags[i];
+ // lookup for exact match, else scan if it's sequenced.
+ if (der.getTag() != expectedTag) {
+ der = der.hasNext() ? der.choose(expectedTag) : null;
+ }
+ if (der == null) {
+ StringBuilder sb = new StringBuilder("Tag not found:");
+ for (int ii = 0; ii <= i; ii++) {
+ sb.append(" 0x").append(Integer.toHexString(tags[ii]));
+ }
+ throw new IllegalStateException(sb.toString());
+ }
+ }
+ return der;
+ }
+
+ String getAsString() {
+ try {
+ return new String(bb.array(), bb.arrayOffset() + bb.position(), bb.remaining(), "UTF-8");
+ } catch (UnsupportedEncodingException e) {
+ throw new IllegalCharsetNameException("UTF-8"); // won't happen.
+ }
+ }
+
+ @Override
+ public int hashCode() {
+ return 31 * tag + bb.hashCode();
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ return (o instanceof DER) && tag == ((DER) o).tag && bb.equals(((DER) o).bb);
+ }
+
+ @Override
+ public boolean hasNext() {
+ // it's a sequence or an embedded octet.
+ return ((tag & 0x30) != 0 || tag == 0x04) && bb.hasRemaining();
+ }
+
+ @Override
+ public DER next() {
+ if (!hasNext()) {
+ throw new NoSuchElementException();
+ }
+ return new DER(bb);
+ }
+
+ @Override
+ public String toString() {
+ return "[tag=0x" + Integer.toHexString(tag) + " bb=" + bb + "]";
+ }
+ }
+}
diff --git a/server-common/src/test/java/com/datastrato/gravitino/server/auth/KerberosTestUtils.java b/server-common/src/test/java/com/datastrato/gravitino/server/auth/KerberosTestUtils.java
new file mode 100644
index 0000000000..acd2aba945
--- /dev/null
+++ b/server-common/src/test/java/com/datastrato/gravitino/server/auth/KerberosTestUtils.java
@@ -0,0 +1,59 @@
+/**
+ * Licensed 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
+ *
+ * <p>http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * <p>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. See accompanying LICENSE file.
+ */
+
+// Referred from Apache Hadoop KerberosTestUtils.java
+// Remove part methods
+// hadoop-common-project/hadoop-auth/src/test/java/org/apache/hadoop/security/\
+// authentication/KerberosTestUtils.java
+
+package com.datastrato.gravitino.server.auth;
+
+import com.datastrato.gravitino.auth.KerberosUtils;
+import java.io.File;
+import java.util.UUID;
+import java.util.concurrent.Callable;
+import javax.security.auth.login.LoginContext;
+
+/** Test helper class for Java Kerberos setup. */
+public class KerberosTestUtils {
+ private static String keytabFile =
+ new File(System.getProperty("test.dir", "target"), UUID.randomUUID().toString())
+ .getAbsolutePath();
+
+ public static String getRealm() {
+ return "EXAMPLE.COM";
+ }
+
+ public static String getClientPrincipal() {
+ return "[email protected]";
+ }
+
+ public static String getServerPrincipal() {
+ return "HTTP/[email protected]";
+ }
+
+ public static String getKeytabFile() {
+ return keytabFile;
+ }
+
+ public static <T> T doAsClient(Callable<T> callable) throws Exception {
+ LoginContext context = null;
+ try {
+ context = KerberosUtils.login(getClientPrincipal(), getKeytabFile());
+ return KerberosUtils.doAs(context.getSubject(), callable);
+ } finally {
+ if (context != null) {
+ context.logout();
+ }
+ }
+ }
+}
diff --git a/server-common/src/test/java/com/datastrato/gravitino/server/auth/TestKerberosAuthenticator.java b/server-common/src/test/java/com/datastrato/gravitino/server/auth/TestKerberosAuthenticator.java
new file mode 100644
index 0000000000..1856552d74
--- /dev/null
+++ b/server-common/src/test/java/com/datastrato/gravitino/server/auth/TestKerberosAuthenticator.java
@@ -0,0 +1,170 @@
+/*
+ * Copyright 2024 Datastrato Pvt Ltd.
+ * This software is licensed under the Apache License version 2.
+ */
+
+package com.datastrato.gravitino.server.auth;
+
+import static com.datastrato.gravitino.server.auth.KerberosConfig.KEYTAB;
+import static com.datastrato.gravitino.server.auth.KerberosConfig.PRINCIPAL;
+
+import com.datastrato.gravitino.Config;
+import com.datastrato.gravitino.auth.AuthConstants;
+import com.datastrato.gravitino.auth.KerberosUtils;
+import com.datastrato.gravitino.exceptions.UnauthorizedException;
+import java.io.File;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.concurrent.Callable;
+import org.apache.hadoop.minikdc.KerberosSecurityTestcase;
+import org.ietf.jgss.GSSContext;
+import org.ietf.jgss.GSSManager;
+import org.ietf.jgss.GSSName;
+import org.ietf.jgss.Oid;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+public class TestKerberosAuthenticator extends KerberosSecurityTestcase {
+
+ @BeforeEach
+ public void setup() throws Exception {
+ startMiniKdc();
+ }
+
+ @AfterEach
+ public void teardown() throws Exception {
+ stopMiniKdc();
+ }
+
+ @Test
+ public void testAuthenticatorInitialization() throws Exception {
+ KerberosAuthenticator kerberosAuthenticator = new KerberosAuthenticator();
+
+ // case 1: lack different parameters
+ Config config = new Config(false) {};
+ Exception e =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ kerberosAuthenticator.initialize(config);
+ });
+ Assertions.assertTrue(e.getMessage().contains("The value can't be blank"));
+
+ config.set(PRINCIPAL, KerberosTestUtils.getServerPrincipal());
+ e =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ kerberosAuthenticator.initialize(config);
+ });
+ Assertions.assertTrue(e.getMessage().contains("The value can't be blank"));
+
+ // case 2: keytab file doesn't exist
+ config.set(KEYTAB, KerberosTestUtils.getKeytabFile());
+ e =
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> {
+ kerberosAuthenticator.initialize(config);
+ });
+ Assertions.assertTrue(e.getMessage().contains("doesn't exist"));
+
+ initKeyTab();
+ kerberosAuthenticator.initialize(config);
+ }
+
+ @Test
+ public void testAuthenticationWithException() throws Exception {
+ // case 1: Empty token authorization header
+ KerberosAuthenticator kerberosAuthenticator = new KerberosAuthenticator();
+ Config config = new Config(false) {};
+ config.set(PRINCIPAL, KerberosTestUtils.getServerPrincipal());
+ config.set(KEYTAB, KerberosTestUtils.getKeytabFile());
+ initKeyTab();
+ kerberosAuthenticator.initialize(config);
+ Assertions.assertTrue(kerberosAuthenticator.isDataFromToken());
+ Exception e =
+ Assertions.assertThrows(
+ UnauthorizedException.class, () -> kerberosAuthenticator.authenticateToken(null));
+ Assertions.assertEquals("Empty token authorization header", e.getMessage());
+
+ // case2 : Invalid token authorization header
+ e =
+ Assertions.assertThrows(
+ UnauthorizedException.class,
+ () -> kerberosAuthenticator.authenticateToken("Xx".getBytes(StandardCharsets.UTF_8)));
+ Assertions.assertEquals("Invalid token authorization header", e.getMessage());
+
+ // case 3: Blank token found
+ e =
+ Assertions.assertThrows(
+ UnauthorizedException.class,
+ () ->
+ kerberosAuthenticator.authenticateToken(
+ AuthConstants.AUTHORIZATION_NEGOTIATE_HEADER.getBytes(StandardCharsets.UTF_8)));
+ Assertions.assertEquals("Blank token found", e.getMessage());
+
+ // case 4: Fail to validate the token
+ e =
+ Assertions.assertThrows(
+ UnauthorizedException.class,
+ () ->
+ kerberosAuthenticator.authenticateToken(
+ (AuthConstants.AUTHORIZATION_NEGOTIATE_HEADER + "xxxx")
+ .getBytes(StandardCharsets.UTF_8)));
+ Assertions.assertEquals("Fail to validate the token", e.getMessage());
+ }
+
+ @Test
+ public void testAuthenticationNormally() throws Exception {
+ KerberosAuthenticator kerberosAuthenticator = new KerberosAuthenticator();
+ Config config = new Config(false) {};
+ config.set(PRINCIPAL, KerberosTestUtils.getServerPrincipal());
+ config.set(KEYTAB, KerberosTestUtils.getKeytabFile());
+ initKeyTab();
+ kerberosAuthenticator.initialize(config);
+ String token =
+ KerberosTestUtils.doAsClient(
+ new Callable<String>() {
+ @Override
+ public String call() throws Exception {
+ GSSManager gssManager = GSSManager.getInstance();
+ GSSContext gssContext = null;
+ try {
+ String servicePrincipal = KerberosTestUtils.getServerPrincipal();
+ Oid oid = KerberosUtils.NT_GSS_KRB5_PRINCIPAL_OID;
+ GSSName serviceName = gssManager.createName(servicePrincipal, oid);
+ oid = KerberosUtils.GSS_KRB5_MECH_OID;
+ gssContext =
+ gssManager.createContext(serviceName, oid, null, GSSContext.DEFAULT_LIFETIME);
+ gssContext.requestCredDeleg(true);
+ gssContext.requestMutualAuth(true);
+
+ byte[] inToken = new byte[0];
+ byte[] outToken = gssContext.initSecContext(inToken, 0, inToken.length);
+ return Base64.getEncoder().encodeToString(outToken);
+
+ } finally {
+ if (gssContext != null) {
+ gssContext.dispose();
+ }
+ }
+ }
+ });
+ kerberosAuthenticator.authenticateToken(
+ (AuthConstants.AUTHORIZATION_NEGOTIATE_HEADER + token).getBytes(StandardCharsets.UTF_8));
+ }
+
+ private void initKeyTab() throws Exception {
+ File keytabFile = new File(KerberosTestUtils.getKeytabFile());
+ String clientPrincipal = removeRealm(KerberosTestUtils.getClientPrincipal());
+ String serverPrincipal = removeRealm(KerberosTestUtils.getServerPrincipal());
+ getKdc().createPrincipal(keytabFile, clientPrincipal, serverPrincipal);
+ }
+
+ private String removeRealm(String principal) {
+ return principal.substring(0, principal.lastIndexOf("@"));
+ }
+}