Skip to content

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

[#737] feat(client): Client supports OAuth 2.0 (#836)

qqqttt123996505a120ea
diff --git a/LICENSE b/LICENSE
index f46b9f2b61..7250fa3a3e 100644
--- a/LICENSE
+++ b/LICENSE
@@ -237,6 +237,8 @@
./common/src/main/java/com/datastrato/gravitino/rest/RESTMessage.java
./core/src/main/java/com/datastrato/gravitino/util/ClientPool.java
./core/src/main/java/com/datastrato/gravitino/util/ClientPoolImpl.java
+ ./common/src/main/java/com/datastrato/gravitino/dto/responses/OAuth2TokenResponse.java
+ ./clients/client-java/src/main/java/com/datastrato/gravitino/client/OAuth2ClientUtil.java
Apache Hive
diff --git a/api/src/main/java/com/datastrato/gravitino/exceptions/BadRequestException.java b/api/src/main/java/com/datastrato/gravitino/exceptions/BadRequestException.java
new file mode 100644
index 0000000000..3d327b420c
--- /dev/null
+++ b/api/src/main/java/com/datastrato/gravitino/exceptions/BadRequestException.java
@@ -0,0 +1,15 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.exceptions;
+
+public class BadRequestException extends GravitinoRuntimeException {
+ public BadRequestException(String message) {
+ super(message);
+ }
+
+ public BadRequestException(String message, Throwable cause) {
+ super(message, cause);
+ }
+}
diff --git a/clients/client-java/build.gradle.kts b/clients/client-java/build.gradle.kts
index 0609e73ea2..ac2fb658f4 100644
--- a/clients/client-java/build.gradle.kts
+++ b/clients/client-java/build.gradle.kts
@@ -36,4 +36,5 @@ dependencies {
testImplementation(libs.mockito.core)
testImplementation(libs.mockserver.netty)
testImplementation(libs.mockserver.client.java)
+ testImplementation(libs.bundles.jwt)
}
diff --git a/clients/client-java/src/main/java/com/datastrato/gravitino/client/AuthDataProvider.java b/clients/client-java/src/main/java/com/datastrato/gravitino/client/AuthDataProvider.java
new file mode 100644
index 0000000000..d549f88417
--- /dev/null
+++ b/clients/client-java/src/main/java/com/datastrato/gravitino/client/AuthDataProvider.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+package com.datastrato.gravitino.client;
+
+import java.io.Closeable;
+
+/** The provider of authentication data */
+interface AuthDataProvider extends Closeable {
+
+ /**
+ * Judge whether AuthDataProvider can provide token data.
+ *
+ * @return true if the AuthDataProvider can provide token data otherwise false.
+ */
+ default boolean hasTokenData() {
+ return false;
+ }
+
+ /**
+ * Acquire the data of token for authentication. The client will set the token data as HTTP header
+ * Authorization directly. So the return value should ensure token data contain the token header
+ * (eg: Bearer, Basic) if necessary.
+ *
+ * @return the token data is used for authentication.
+ */
+ default byte[] getTokenData() {
+ return null;
+ }
+}
diff --git a/clients/client-java/src/main/java/com/datastrato/gravitino/client/DefaultOAuth2TokenProvider.java b/clients/client-java/src/main/java/com/datastrato/gravitino/client/DefaultOAuth2TokenProvider.java
new file mode 100644
index 0000000000..a119700934
--- /dev/null
+++ b/clients/client-java/src/main/java/com/datastrato/gravitino/client/DefaultOAuth2TokenProvider.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.client;
+
+import com.google.common.base.Preconditions;
+import java.util.Collections;
+import org.apache.commons.lang3.StringUtils;
+
+/** This class is the default implement of OAuth2TokenProvider. */
+public class DefaultOAuth2TokenProvider extends OAuth2TokenProvider {
+
+ private String credential;
+ private String scope;
+ private String path;
+ private String token;
+
+ private DefaultOAuth2TokenProvider() {}
+
+ @Override
+ protected String getAccessToken() {
+ synchronized (this) {
+ Long expires = OAuth2ClientUtil.expiresAtMillis(token);
+ if (expires == null) {
+ return null;
+ }
+ if (expires > System.currentTimeMillis()) {
+ return token;
+ }
+ token =
+ OAuth2ClientUtil.fetchToken(client, Collections.emptyMap(), credential, scope, path)
+ .getAccessToken();
+ return token;
+ }
+ }
+
+ /**
+ * Creates a new instance of the DefaultOAuth2TokenProvider.Builder
+ *
+ * @return A new instance of DefaultOAuth2TokenProvider.Builder
+ */
+ public static Builder builder() {
+ return new Builder();
+ }
+
+ /* Builder class for configuring and creating instances of DefaultOAuth2TokenProvider. */
+ public static class Builder
+ extends OAuth2TokenProviderBuilder<Builder, DefaultOAuth2TokenProvider> {
+
+ private String credential;
+ private String scope;
+ private String path;
+
+ /**
+ * Sets the scope for the HTTP token requests.
+ *
+ * @param scope The scope for the HTTP token requests.
+ * @return This Builder instance for method chaining.
+ */
+ public Builder withScope(String scope) {
+ this.scope = scope;
+ return this;
+ }
+
+ /**
+ * Sets the path for the HTTP token requests.
+ *
+ * @param path The path for the HTTP token requests.
+ * @return This Builder instance for method chaining.
+ */
+ public Builder withPath(String path) {
+ this.path = path;
+ return this;
+ }
+
+ /**
+ * Sets the credential for the HTTP token requests.
+ *
+ * @param credential The credential for the HTTP token requests.
+ * @return This Builder instance for method chaining.
+ */
+ public Builder withCredential(String credential) {
+ this.credential = credential;
+ return this;
+ }
+
+ @Override
+ protected DefaultOAuth2TokenProvider internalBuild() {
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(credential), "OAuthDataProvider must set credential");
+ Preconditions.checkArgument(
+ StringUtils.isNotBlank(scope), "OAuthDataProvider must set scope");
+ Preconditions.checkArgument(StringUtils.isNotBlank(path), "OAuthDataProvider must set path");
+ DefaultOAuth2TokenProvider provider = new DefaultOAuth2TokenProvider();
+ provider.client = client;
+ provider.credential = credential;
+ provider.scope = scope;
+ provider.path = path;
+ provider.token =
+ OAuth2ClientUtil.fetchToken(client, Collections.emptyMap(), credential, scope, path)
+ .getAccessToken();
+ return provider;
+ }
+ }
+}
diff --git a/clients/client-java/src/main/java/com/datastrato/gravitino/client/ErrorHandlers.java b/clients/client-java/src/main/java/com/datastrato/gravitino/client/ErrorHandlers.java
index 50f0700a07..518ec6d1a7 100644
--- a/clients/client-java/src/main/java/com/datastrato/gravitino/client/ErrorHandlers.java
+++ b/clients/client-java/src/main/java/com/datastrato/gravitino/client/ErrorHandlers.java
@@ -6,6 +6,8 @@ package com.datastrato.gravitino.client;
import com.datastrato.gravitino.dto.responses.ErrorConstants;
import com.datastrato.gravitino.dto.responses.ErrorResponse;
+import com.datastrato.gravitino.dto.responses.OAuth2ErrorResponse;
+import com.datastrato.gravitino.exceptions.BadRequestException;
import com.datastrato.gravitino.exceptions.CatalogAlreadyExistsException;
import com.datastrato.gravitino.exceptions.MetalakeAlreadyExistsException;
import com.datastrato.gravitino.exceptions.NoSuchCatalogException;
@@ -17,6 +19,7 @@ import com.datastrato.gravitino.exceptions.NotFoundException;
import com.datastrato.gravitino.exceptions.RESTException;
import com.datastrato.gravitino.exceptions.SchemaAlreadyExistsException;
import com.datastrato.gravitino.exceptions.TableAlreadyExistsException;
+import com.datastrato.gravitino.exceptions.UnauthorizedException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.base.Joiner;
import java.util.List;
@@ -73,6 +76,10 @@ public class ErrorHandlers {
return RestErrorHandler.INSTANCE;
}
+ public static Consumer<ErrorResponse> oauthErrorHandler() {
+ return OAuthErrorHandler.INSTANCE;
+ }
+
private ErrorHandlers() {}
/**
@@ -231,6 +238,44 @@ public class ErrorHandlers {
}
}
+ public static class OAuthErrorHandler extends RestErrorHandler {
+ private static final ErrorHandler INSTANCE = new OAuthErrorHandler();
+
+ @Override
+ public ErrorResponse parseResponse(int code, String json, ObjectMapper mapper) {
+ try {
+ OAuth2ErrorResponse response = mapper.readValue(json, OAuth2ErrorResponse.class);
+ return ErrorResponse.oauthError(code, response.getType(), response.getMessage());
+ } catch (Exception x) {
+ LOG.warn("Unable to parse error response", x);
+ }
+ String errorMsg = String.format("Error code: %d, message: %s", code, json);
+ return ErrorResponse.unknownError(errorMsg);
+ }
+
+ @Override
+ public void accept(ErrorResponse errorResponse) {
+ if (errorResponse.getType() != null) {
+ switch (errorResponse.getType()) {
+ case OAuth2ClientUtil.INVALID_CLIENT_ERROR:
+ throw new UnauthorizedException(
+ String.format(
+ "Not authorized: %s: %s", errorResponse.getType(), errorResponse.getMessage()));
+ case OAuth2ClientUtil.INVALID_REQUEST_ERROR:
+ case OAuth2ClientUtil.INVALID_GRANT_ERROR:
+ case OAuth2ClientUtil.UNAUTHORIZED_CLIENT_ERROR:
+ case OAuth2ClientUtil.UNSUPPORTED_GRANT_TYPE_ERROR:
+ case OAuth2ClientUtil.INVALID_SCOPE_ERROR:
+ throw new BadRequestException(
+ String.format(
+ "Malformed request: %s: %s",
+ errorResponse.getType(), errorResponse.getMessage()));
+ }
+ }
+ super.accept(errorResponse);
+ }
+ }
+
/** Generic error handler for REST requests. */
private static class RestErrorHandler extends ErrorHandler {
private static final ErrorHandler INSTANCE = new RestErrorHandler();
diff --git a/clients/client-java/src/main/java/com/datastrato/gravitino/client/GravitinoClient.java b/clients/client-java/src/main/java/com/datastrato/gravitino/client/GravitinoClient.java
index 87c2ab1ebe..a364433c92 100644
--- a/clients/client-java/src/main/java/com/datastrato/gravitino/client/GravitinoClient.java
+++ b/clients/client-java/src/main/java/com/datastrato/gravitino/client/GravitinoClient.java
@@ -45,13 +45,18 @@ public class GravitinoClient implements SupportsMetalakes, Closeable {
private final RESTClient restClient;
/**
- * Constructs a new GravitinoClient with the given URI.
+ * Constructs a new GravitinoClient with the given URI, authenticator and AuthDataProvider.
*
* @param uri The base URI for the Gravitino API.
+ * @param authenticator The type of authenticator.
+ * @param authDataProvider The provider of the data which is used for authentication.
*/
- private GravitinoClient(String uri) {
+ private GravitinoClient(String uri, AuthDataProvider authDataProvider) {
this.restClient =
- HTTPClient.builder(Collections.emptyMap()).uri(uri).withObjectMapper(MAPPER).build();
+ HTTPClient.builder(Collections.emptyMap())
+ .uri(uri)
+ .withAuthDataProvider(authDataProvider)
+ .build();
}
/**
@@ -225,6 +230,7 @@ public class GravitinoClient implements SupportsMetalakes, Closeable {
public static class Builder {
private String uri;
+ private AuthDataProvider authDataProvider;
/**
* Private constructor for the Builder class.
@@ -235,6 +241,28 @@ public class GravitinoClient implements SupportsMetalakes, Closeable {
this.uri = uri;
}
+ /**
+ * Sets the simple mode authentication for the Graivitno
+ *
+ * @return This Builder instance for method chaining.
+ */
+ public Builder withSimpleAuth() {
+ this.authDataProvider = new SimpleTokenProvider();
+ return this;
+ }
+
+ /**
+ * Sets OAuth2TokenProvider for the GravitinoClient.
+ *
+ * @param dataProvider The OAuth2TokenProvider used as the provider of authentication data for
+ * GravitinoClient.
+ * @return This Builder instance for method chaining.
+ */
+ public Builder withOAuth(OAuth2TokenProvider dataProvider) {
+ this.authDataProvider = dataProvider;
+ return this;
+ }
+
/**
* Builds a new GravitinoClient instance.
*
@@ -245,7 +273,7 @@ public class GravitinoClient implements SupportsMetalakes, Closeable {
Preconditions.checkArgument(
uri != null && !uri.isEmpty(), "The argument 'uri' must be a valid URI");
- return new GravitinoClient(uri);
+ return new GravitinoClient(uri, authDataProvider);
}
}
}
diff --git a/clients/client-java/src/main/java/com/datastrato/gravitino/client/HTTPClient.java b/clients/client-java/src/main/java/com/datastrato/gravitino/client/HTTPClient.java
index bf481b982e..60773cbd49 100644
--- a/clients/client-java/src/main/java/com/datastrato/gravitino/client/HTTPClient.java
+++ b/clients/client-java/src/main/java/com/datastrato/gravitino/client/HTTPClient.java
@@ -19,6 +19,7 @@
package com.datastrato.gravitino.client;
+import com.datastrato.gravitino.auth.AuthConstants;
import com.datastrato.gravitino.dto.responses.ErrorResponse;
import com.datastrato.gravitino.exceptions.RESTException;
import com.datastrato.gravitino.json.JsonUtils;
@@ -75,6 +76,7 @@ public class HTTPClient implements RESTClient {
private final String uri;
private final CloseableHttpClient httpClient;
private final ObjectMapper mapper;
+ private final AuthDataProvider authDataProvider;
/**
* Constructs an instance of HTTPClient with the provided information.
@@ -82,8 +84,13 @@ public class HTTPClient implements RESTClient {
* @param uri The base URI of the REST API.
* @param baseHeaders A map of base headers to be included in all HTTP requests.
* @param objectMapper The ObjectMapper used for JSON serialization and deserialization.
+ * @param authDataProvider The provider of authentication data.
*/
- private HTTPClient(String uri, Map<String, String> baseHeaders, ObjectMapper objectMapper) {
+ private HTTPClient(
+ String uri,
+ Map<String, String> baseHeaders,
+ ObjectMapper objectMapper,
+ AuthDataProvider authDataProvider) {
this.uri = uri;
this.mapper = objectMapper;
@@ -97,6 +104,7 @@ public class HTTPClient implements RESTClient {
}
this.httpClient = clientBuilder.build();
+ this.authDataProvider = authDataProvider;
}
/**
@@ -322,6 +330,10 @@ public class HTTPClient implements RESTClient {
} else {
addRequestHeaders(request, headers, ContentType.APPLICATION_JSON.getMimeType());
}
+ if (authDataProvider != null) {
+ request.setHeader(
+ AuthConstants.HTTP_HEADER_AUTHORIZATION, new String(authDataProvider.getTokenData()));
+ }
try (CloseableHttpResponse response = httpClient.execute(request)) {
Map<String, String> respHeaders = Maps.newHashMap();
@@ -607,6 +619,9 @@ public class HTTPClient implements RESTClient {
*/
@Override
public void close() throws IOException {
+ if (authDataProvider != null) {
+ authDataProvider.close();
+ }
httpClient.close(CloseMode.GRACEFUL);
}
@@ -631,6 +646,7 @@ public class HTTPClient implements RESTClient {
private final Map<String, String> baseHeaders = Maps.newHashMap();
private String uri;
private ObjectMapper mapper = JsonUtils.objectMapper();
+ private AuthDataProvider authDataProvider;
private Builder(Map<String, String> properties) {
this.properties = properties;
@@ -683,13 +699,25 @@ public class HTTPClient implements RESTClient {
return this;
}
+ /**
+ * Sets the AuthDataProvider for the HTTP client.
+ *
+ * @param authDataProvider The authDataProvider providing the data used to authenticate.
+ * @return This Builder instance for method chaining.
+ */
+ public Builder withAuthDataProvider(AuthDataProvider authDataProvider) {
+ this.authDataProvider = authDataProvider;
+ return this;
+ }
+
/**
* Builds and returns an instance of the HTTPClient with the configured options.
*
* @return An instance of HTTPClient with the configured options.
*/
public HTTPClient build() {
- return new HTTPClient(uri, baseHeaders, mapper);
+
+ return new HTTPClient(uri, baseHeaders, mapper, authDataProvider);
}
}
diff --git a/clients/client-java/src/main/java/com/datastrato/gravitino/client/OAuth2ClientUtil.java b/clients/client-java/src/main/java/com/datastrato/gravitino/client/OAuth2ClientUtil.java
new file mode 100644
index 0000000000..463b0ccd8b
--- /dev/null
+++ b/clients/client-java/src/main/java/com/datastrato/gravitino/client/OAuth2ClientUtil.java
@@ -0,0 +1,146 @@
+/*
+ * 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 com.datastrato.gravitino.client;
+
+import com.datastrato.gravitino.dto.responses.OAuth2TokenResponse;
+import com.datastrato.gravitino.json.JsonUtils;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.google.common.base.Joiner;
+import com.google.common.base.Preconditions;
+import com.google.common.base.Splitter;
+import com.google.common.collect.ImmutableList;
+import com.google.common.collect.ImmutableMap;
+import java.io.IOException;
+import java.util.Base64;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import org.apache.commons.lang3.tuple.Pair;
+
+// Referred from Apache Iceberg's OAuth2Util implementation
+// core/src/main/java/org/apache/iceberg/rest/OAuth2Util.java
+class OAuth2ClientUtil {
+
+ public static final String SCOPE = "scope";
+ private static final Splitter CREDENTIAL_SPLITTER = Splitter.on(":").limit(2).trimResults();
+ private static final String GRANT_TYPE = "grant_type";
+ private static final String CLIENT_CREDENTIALS = "client_credentials";
+
+ private static final String CLIENT_ID = "client_id";
+ private static final String CLIENT_SECRET = "client_secret";
+
+ // error type constants
+ public static final String INVALID_REQUEST_ERROR = "invalid_request";
+ public static final String INVALID_CLIENT_ERROR = "invalid_client";
+ public static final String INVALID_GRANT_ERROR = "invalid_grant";
+ public static final String UNAUTHORIZED_CLIENT_ERROR = "unauthorized_client";
+ public static final String UNSUPPORTED_GRANT_TYPE_ERROR = "unsupported_grant_type";
+ public static final String INVALID_SCOPE_ERROR = "invalid_scope";
+
+ private OAuth2ClientUtil() {}
+
+ public static OAuth2TokenResponse fetchToken(
+ RESTClient client,
+ Map<String, String> headers,
+ String credential,
+ String scope,
+ String path) {
+ Map<String, String> request =
+ clientCredentialsRequest(
+ credential, scope != null ? ImmutableList.of(scope) : ImmutableList.of());
+
+ OAuth2TokenResponse response =
+ client.postForm(
+ path, request, OAuth2TokenResponse.class, headers, ErrorHandlers.oauthErrorHandler());
+ response.validate();
+
+ return response;
+ }
+
+ private static Pair<String, String> parseCredential(String credential) {
+ Preconditions.checkNotNull(credential, "Invalid credential: null");
+ List<String> parts = CREDENTIAL_SPLITTER.splitToList(credential);
+ switch (parts.size()) {
+ case 2:
+ // client ID and client secret
+ return Pair.of(parts.get(0), parts.get(1));
+ case 1:
+ // client secret
+ return Pair.of(null, parts.get(0));
+ default:
+ // this should never happen because the credential splitter is limited to 2
+ throw new IllegalArgumentException("Invalid credential: " + credential);
+ }
+ }
+
+ private static Map<String, String> clientCredentialsRequest(
+ String credential, List<String> scopes) {
+ Pair<String, String> credentialPair = parseCredential(credential);
+ return clientCredentialsRequest(credentialPair.getLeft(), credentialPair.getRight(), scopes);
+ }
+
+ private static Map<String, String> clientCredentialsRequest(
+ String clientId, String clientSecret, List<String> scopes) {
+ ImmutableMap.Builder<String, String> formData = ImmutableMap.builder();
+ formData.put(GRANT_TYPE, CLIENT_CREDENTIALS);
+ if (clientId != null) {
+ formData.put(CLIENT_ID, clientId);
+ }
+ formData.put(CLIENT_SECRET, clientSecret);
+ formData.put(SCOPE, toScope(scopes));
+
+ return formData.build();
+ }
+
+ /**
+ * If the token is a JWT, extracts the expiration timestamp from the ext claim or null.
+ *
+ * @param token a token String
+ * @return The epoch millisecond the token expires at or null if it's not a valid JWT.
+ */
+ static Long expiresAtMillis(String token) {
+ if (null == token) {
+ return null;
+ }
+
+ List<String> parts = Splitter.on('.').splitToList(token);
+ if (parts.size() != 3) {
+ return null;
+ }
+
+ JsonNode node;
+ try {
+ node = JsonUtils.objectMapper().readTree(Base64.getUrlDecoder().decode(parts.get(1)));
+ } catch (IOException e) {
+ return null;
+ }
+
+ String property = "exp";
+ if (!node.has(property) || node.get(property).isNull()) {
+ return null;
+ }
+ return TimeUnit.SECONDS.toMillis(JsonUtils.getLong(property, node));
+ }
+
+ private static final Joiner SCOPE_JOINER = Joiner.on(" ");
+
+ public static String toScope(Iterable<String> scopes) {
+ return SCOPE_JOINER.join(scopes);
+ }
+}
diff --git a/clients/client-java/src/main/java/com/datastrato/gravitino/client/OAuth2TokenProvider.java b/clients/client-java/src/main/java/com/datastrato/gravitino/client/OAuth2TokenProvider.java
new file mode 100644
index 0000000000..1bf74a57dd
--- /dev/null
+++ b/clients/client-java/src/main/java/com/datastrato/gravitino/client/OAuth2TokenProvider.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+package com.datastrato.gravitino.client;
+
+import com.datastrato.gravitino.auth.AuthConstants;
+import com.google.common.base.Preconditions;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import org.apache.commons.lang3.StringUtils;
+
+/**
+ * OAuthDataProvider will request the access token from the authorization server and then provide
+ * the access token for every request.
+ */
+public abstract class OAuth2TokenProvider implements AuthDataProvider {
+
+ protected HTTPClient client;
+
+ /**
+ * Judge whether AuthDataProvider can provide token data.
+ *
+ * @return true if the AuthDataProvider can provide token data otherwise false.
+ */
+ @Override
+ public boolean hasTokenData() {
+ return true;
+ }
+
+ /**
+ * Acquire the data of token for authentication. The client will set the token data as HTTP header
+ * Authorization directly. So the return value should ensure token data contain the token header
+ * (eg: Bearer, Basic) if necessary.
+ *
+ * @return the token data is used for authentication.
+ */
+ @Override
+ public byte[] getTokenData() {
+ String accessToken = getAccessToken();
+ if (accessToken == null) {
+ return null;
+ }
+ return (AuthConstants.AUTHORIZATION_BEARER_HEADER + getAccessToken())
+ .getBytes(StandardCharsets.UTF_8);
+ }
+
+ /** Closes the OAuth2TokenProvider and releases any underlying resources. */
+ @Override
+ public void close() throws IOException {
+ if (client != null) {
+ client.close();
+ }
+ }
+
+ protected abstract String getAccessToken();
+
+ interface Builder<SELF extends Builder<SELF, T>, T extends OAuth2TokenProvider> {
+ SELF withUri(String uri);
+
+ T build();
+ }
+
+ /**
+ * Builder interface for creating instances of {@link OAuth2TokenProvider}.
+ *
+ * @param <SELF> The type of the builder.
+ * @param <T> The type of the OAuth2TokenProvider being built.
+ */
+ public abstract static class OAuth2TokenProviderBuilder<
+ SELF extends Builder<SELF, T>, T extends OAuth2TokenProvider>
+ implements Builder<SELF, T> {
+
+ private String uri;
+ protected HTTPClient client;
+
+ /**
+ * Sets the uri of the OAuth2TokenProvider
+ *
+ * @param uri The uri of oauth server .
+ * @return The builder instance.
+ */
+ @Override
+ public SELF withUri(String uri) {
+ this.uri = uri;
+ return self();
+ }
+
+ /**
+ * Builds the instance of the OAuth2TokenProvider.
+ *
+ * @return The built OAuth2TokenProvider instance.
+ */
+ @Override
+ public T build() {
+ Preconditions.checkArgument(StringUtils.isNotBlank(uri), "OAuthDataProvider must set url");
+ client = HTTPClient.builder(Collections.emptyMap()).uri(uri).build();
+ T t = internalBuild();
+ return t;
+ }
+
+ private SELF self() {
+ return (SELF) this;
+ }
+
+ protected abstract T internalBuild();
+ }
+}
diff --git a/clients/client-java/src/main/java/com/datastrato/gravitino/client/SimpleTokenProvider.java b/clients/client-java/src/main/java/com/datastrato/gravitino/client/SimpleTokenProvider.java
new file mode 100644
index 0000000000..24a57179a9
--- /dev/null
+++ b/clients/client-java/src/main/java/com/datastrato/gravitino/client/SimpleTokenProvider.java
@@ -0,0 +1,48 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+package com.datastrato.gravitino.client;
+
+import com.datastrato.gravitino.auth.AuthConstants;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+
+/* *
+ * SimpleAuthProvider will use the environment variable `GRAVITINO_USER` or
+ * the user of the system to generate a basic token for every request.
+ */
+final class SimpleTokenProvider implements AuthDataProvider {
+
+ private final byte[] token;
+
+ public SimpleTokenProvider() {
+ String gravitinoUser = System.getenv("GRAVITINO_USER");
+ if (gravitinoUser == null) {
+ gravitinoUser = System.getProperty("user.name");
+ }
+ String userInformation = gravitinoUser + ":dummy";
+ this.token =
+ (AuthConstants.AUTHORIZATION_BASIC_HEADER
+ + new String(
+ Base64.getEncoder().encode(userInformation.getBytes(StandardCharsets.UTF_8))))
+ .getBytes(StandardCharsets.UTF_8);
+ }
+
+ @Override
+ public boolean hasTokenData() {
+ return true;
+ }
+
+ @Override
+ public byte[] getTokenData() {
+ return token;
+ }
+
+ @Override
+ public void close() throws IOException {
+ // no op
+ }
+}
diff --git a/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestOAuth2TokenProvider.java b/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestOAuth2TokenProvider.java
new file mode 100644
index 0000000000..37515cffa8
--- /dev/null
+++ b/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestOAuth2TokenProvider.java
@@ -0,0 +1,144 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+package com.datastrato.gravitino.client;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockserver.integration.ClientAndServer.startClientAndServer;
+
+import com.datastrato.gravitino.auth.AuthConstants;
+import com.datastrato.gravitino.dto.responses.OAuth2ErrorResponse;
+import com.datastrato.gravitino.dto.responses.OAuth2TokenResponse;
+import com.datastrato.gravitino.exceptions.BadRequestException;
+import com.datastrato.gravitino.exceptions.UnauthorizedException;
+import com.datastrato.gravitino.json.JsonUtils;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureAlgorithm;
+import io.jsonwebtoken.security.Keys;
+import java.io.IOException;
+import java.security.KeyPair;
+import java.util.Date;
+import org.apache.hc.core5.http.HttpStatus;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.mockserver.integration.ClientAndServer;
+import org.mockserver.matchers.Times;
+import org.mockserver.model.HttpResponse;
+
+public class TestOAuth2TokenProvider {
+
+ private static final int PORT = 1082;
+ private static ClientAndServer mockServer;
+
+ @BeforeAll
+ public static void beforeClass() {
+ mockServer = startClientAndServer(PORT);
+ }
+
+ @AfterAll
+ public static void stopServer() throws IOException {
+ mockServer.stop();
+ }
+
+ @Test
+ public void testProviderInitException() throws Exception {
+
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> DefaultOAuth2TokenProvider.builder().withUri("test").build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () -> DefaultOAuth2TokenProvider.builder().withUri("test").withCredential("xx").build());
+ Assertions.assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ DefaultOAuth2TokenProvider.builder()
+ .withUri("test")
+ .withCredential("xx")
+ .withScope("test")
+ .build());
+ }
+
+ @Test
+ public void testAuthenticationError() throws Exception {
+
+ HttpResponse mockResponse =
+ HttpResponse.response().withStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
+ OAuth2ErrorResponse respBody =
+ new OAuth2ErrorResponse(OAuth2ClientUtil.INVALID_CLIENT_ERROR, "invalid");
+ String respJson = JsonUtils.objectMapper().writeValueAsString(respBody);
+ mockResponse = mockResponse.withBody(respJson);
+ mockServer.when(any(), Times.exactly(1)).respond(mockResponse);
+ OAuth2TokenProvider.Builder builder =
+ DefaultOAuth2TokenProvider.builder()
+ .withUri(String.format("http://127.0.0.1:%d", PORT))
+ .withCredential("yy:xx")
+ .withPath("oauth/token")
+ .withScope("test");
+ Assertions.assertThrows(UnauthorizedException.class, builder::build);
+
+ respBody = new OAuth2ErrorResponse(OAuth2ClientUtil.INVALID_GRANT_ERROR, "invalid");
+ respJson = JsonUtils.objectMapper().writeValueAsString(respBody);
+ mockResponse = mockResponse.withBody(respJson);
+ mockServer.when(any(), Times.exactly(1)).respond(mockResponse);
+ Assertions.assertThrows(BadRequestException.class, builder::build);
+ }
+
+ @Test
+ public void testAuthenticationNormal() throws Exception {
+ OAuth2TokenProvider.Builder builder =
+ DefaultOAuth2TokenProvider.builder()
+ .withUri(String.format("http://127.0.0.1:%d", PORT))
+ .withCredential("yy:xx")
+ .withPath("oauth/token")
+ .withScope("test");
+
+ HttpResponse mockResponse = HttpResponse.response().withStatusCode(HttpStatus.SC_OK);
+ OAuth2TokenResponse response = new OAuth2TokenResponse("1", "2", "3", 1, "test", null);
+ String respJson = JsonUtils.objectMapper().writeValueAsString(response);
+ mockResponse = mockResponse.withBody(respJson);
+ mockServer.when(any(), Times.exactly(1)).respond(mockResponse);
+ Assertions.assertThrows(IllegalArgumentException.class, builder::build);
+ response = new OAuth2TokenResponse("1", "2", "bearer", 1, "test", null);
+ respJson = JsonUtils.objectMapper().writeValueAsString(response);
+ mockResponse = mockResponse.withBody(respJson);
+ mockServer.when(any(), Times.exactly(1)).respond(mockResponse);
+ OAuth2TokenProvider provider = builder.build();
+ Assertions.assertTrue(provider.hasTokenData());
+ Assertions.assertNull(provider.getTokenData());
+ KeyPair keyPair = Keys.keyPairFor(SignatureAlgorithm.RS256);
+ String oldAccessToken =
+ Jwts.builder()
+ .setSubject("gravitino")
+ .setExpiration(new Date(System.currentTimeMillis() - 5))
+ .setAudience("service1")
+ .signWith(keyPair.getPrivate(), SignatureAlgorithm.RS256)
+ .compact();
+
+ response = new OAuth2TokenResponse(oldAccessToken, "2", "bearer", 1, "test", null);
+ respJson = JsonUtils.objectMapper().writeValueAsString(response);
+ mockResponse = mockResponse.withBody(respJson);
+ mockServer.when(any(), Times.exactly(1)).respond(mockResponse);
+ provider = builder.build();
+ String accessToken =
+ Jwts.builder()
+ .setSubject("gravitino")
+ .setExpiration(new Date(System.currentTimeMillis() + 10000))
+ .setAudience("service1")
+ .signWith(keyPair.getPrivate(), SignatureAlgorithm.RS256)
+ .compact();
+
+ response = new OAuth2TokenResponse(accessToken, "2", "bearer", 1, "test", null);
+ respJson = JsonUtils.objectMapper().writeValueAsString(response);
+ mockResponse = mockResponse.withBody(respJson);
+ mockServer.when(any(), Times.exactly(1)).respond(mockResponse);
+ Assertions.assertNotEquals(accessToken, oldAccessToken);
+ Assertions.assertEquals(
+ AuthConstants.AUTHORIZATION_BEARER_HEADER + accessToken,
+ new String(provider.getTokenData()));
+ }
+}
diff --git a/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestSimpleTokenProvider.java b/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestSimpleTokenProvider.java
new file mode 100644
index 0000000000..40676f425b
--- /dev/null
+++ b/clients/client-java/src/test/java/com/datastrato/gravitino/client/TestSimpleTokenProvider.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.client;
+
+import com.datastrato.gravitino.auth.AuthConstants;
+import java.io.IOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestSimpleTokenProvider {
+
+ @Test
+ public void testAuthentication() throws IOException {
+ try (AuthDataProvider provider = new SimpleTokenProvider()) {
+ Assertions.assertTrue(provider.hasTokenData());
+ String user = System.getenv("GRAVITINO_USER");
+ String token = new String(provider.getTokenData());
+ Assertions.assertTrue(token.startsWith(AuthConstants.AUTHORIZATION_BASIC_HEADER));
+ String tokenString =
+ new String(
+ Base64.getDecoder()
+ .decode(
+ token
+ .substring(AuthConstants.AUTHORIZATION_BASIC_HEADER.length())
+ .getBytes(StandardCharsets.UTF_8)));
+ if (user != null) {
+ Assertions.assertEquals(user + ":dummy", tokenString);
+ } else {
+ user = System.getProperty("user.name");
+ Assertions.assertEquals(user + ":dummy", tokenString);
+ }
+ }
+ }
+}
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 ceeb7614f0..f7c4507e5c 100644
--- a/common/src/main/java/com/datastrato/gravitino/auth/AuthenticatorType.java
+++ b/common/src/main/java/com/datastrato/gravitino/auth/AuthenticatorType.java
@@ -6,6 +6,7 @@
package com.datastrato.gravitino.auth;
public enum AuthenticatorType {
+ NONE,
SIMPLE,
OAUTH
}
diff --git a/common/src/main/java/com/datastrato/gravitino/dto/responses/ErrorResponse.java b/common/src/main/java/com/datastrato/gravitino/dto/responses/ErrorResponse.java
index b561e03d2f..d7bbd786d5 100644
--- a/common/src/main/java/com/datastrato/gravitino/dto/responses/ErrorResponse.java
+++ b/common/src/main/java/com/datastrato/gravitino/dto/responses/ErrorResponse.java
@@ -134,6 +134,10 @@ public class ErrorResponse extends BaseResponse {
ErrorConstants.UNKNOWN_ERROR_CODE, RuntimeException.class.getSimpleName(), message, null);
}
+ public static ErrorResponse oauthError(int code, String type, String message) {
+ return new ErrorResponse(code, type, message, null);
+ }
+
private static List<String> getStackTrace(Throwable throwable) {
if (throwable == null) {
return null;
diff --git a/common/src/main/java/com/datastrato/gravitino/dto/responses/OAuth2ErrorResponse.java b/common/src/main/java/com/datastrato/gravitino/dto/responses/OAuth2ErrorResponse.java
new file mode 100644
index 0000000000..25874be7d7
--- /dev/null
+++ b/common/src/main/java/com/datastrato/gravitino/dto/responses/OAuth2ErrorResponse.java
@@ -0,0 +1,37 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+
+package com.datastrato.gravitino.dto.responses;
+
+import com.datastrato.gravitino.rest.RESTResponse;
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import javax.annotation.Nullable;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+
+@Getter
+@EqualsAndHashCode
+public class OAuth2ErrorResponse implements RESTResponse {
+ @JsonProperty("error")
+ private String type;
+
+ @Nullable
+ @JsonProperty("error_description")
+ private String message;
+
+ public OAuth2ErrorResponse(String type, String message) {
+ this.type = type;
+ this.message = message;
+ }
+
+ // This is the constructor that is used by Jackson deserializer
+ public OAuth2ErrorResponse() {}
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(type != null, "OAuthErrorResponse should contain type");
+ }
+}
diff --git a/common/src/main/java/com/datastrato/gravitino/dto/responses/OAuth2TokenResponse.java b/common/src/main/java/com/datastrato/gravitino/dto/responses/OAuth2TokenResponse.java
new file mode 100644
index 0000000000..f500540fa3
--- /dev/null
+++ b/common/src/main/java/com/datastrato/gravitino/dto/responses/OAuth2TokenResponse.java
@@ -0,0 +1,90 @@
+/*
+ * 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 com.datastrato.gravitino.dto.responses;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import com.google.common.base.Preconditions;
+import javax.annotation.Nullable;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+import org.apache.commons.lang3.StringUtils;
+
+// Referred from Apache Iceberg's OAuthTokenResponse implementation
+// core/src/main/java/org/apache/iceberg/rest/auth/responses/OAuthTokenResponse.java
+@Getter
+@EqualsAndHashCode(callSuper = true)
+@ToString
+public class OAuth2TokenResponse extends BaseResponse {
+ @JsonProperty("access_token")
+ private final String accessToken;
+
+ @Nullable
+ @JsonProperty("issued_token_type")
+ private final String issuedTokenType;
+
+ @JsonProperty("token_type")
+ private final String tokenType;
+
+ @JsonProperty("expires_in")
+ private final Integer expiresIn;
+
+ @JsonProperty("scope")
+ private final String scope;
+
+ @Nullable
+ @JsonProperty("refresh_token")
+ private final String refreshToken;
+
+ public OAuth2TokenResponse(
+ String accessToken,
+ String issuedTokenType,
+ String tokenType,
+ Integer expiresIn,
+ String scope,
+ String refreshToken) {
+ this.accessToken = accessToken;
+ this.issuedTokenType = issuedTokenType;
+ this.tokenType = tokenType;
+ this.expiresIn = expiresIn;
+ this.scope = scope;
+ this.refreshToken = refreshToken;
+ }
+
+ // This is the constructor that is used by Jackson deserializer
+ public OAuth2TokenResponse() {
+ super();
+ this.accessToken = null;
+ this.issuedTokenType = null;
+ this.tokenType = null;
+ this.expiresIn = null;
+ this.scope = null;
+ this.refreshToken = null;
+ }
+
+ @Override
+ public void validate() throws IllegalArgumentException {
+ Preconditions.checkArgument(StringUtils.isNotBlank(accessToken), "Invalid access token: null");
+ Preconditions.checkArgument(
+ "bearer".equalsIgnoreCase(tokenType),
+ "Unsupported token type: %s (must be \"bearer\")",
+ tokenType);
+ }
+}
diff --git a/common/src/main/java/com/datastrato/gravitino/json/JsonUtils.java b/common/src/main/java/com/datastrato/gravitino/json/JsonUtils.java
index f300bc013f..85ec64f039 100644
--- a/common/src/main/java/com/datastrato/gravitino/json/JsonUtils.java
+++ b/common/src/main/java/com/datastrato/gravitino/json/JsonUtils.java
@@ -253,6 +253,17 @@ public class JsonUtils {
return pNode.asInt();
}
+ public static long getLong(String property, JsonNode node) {
+ Preconditions.checkArgument(node.has(property), "Cannot parse missing property: %s", property);
+ JsonNode pNode = node.get(property);
+ Preconditions.checkArgument(
+ pNode != null && !pNode.isNull() && pNode.isIntegralNumber() && pNode.canConvertToLong(),
+ "Cannot parse to an long value %s: %s",
+ property,
+ pNode);
+ return pNode.asLong();
+ }
+
public static FunctionArg readFunctionArg(JsonNode node) {
Preconditions.checkArgument(
node != null && !node.isNull() && node.isObject(),
diff --git a/common/src/test/java/com/datastrato/gravitino/dto/responses/TestResponses.java b/common/src/test/java/com/datastrato/gravitino/dto/responses/TestResponses.java
index 8ddb38710b..df0405d6fc 100644
--- a/common/src/test/java/com/datastrato/gravitino/dto/responses/TestResponses.java
+++ b/common/src/test/java/com/datastrato/gravitino/dto/responses/TestResponses.java
@@ -198,4 +198,29 @@ public class TestResponses {
ErrorResponse error = ErrorResponse.unknownError("unknown error");
error.validate(); // No exception thrown
}
+
+ @Test
+ void testOAuthTokenResponse() throws IllegalArgumentException {
+ OAuth2TokenResponse response =
+ new OAuth2TokenResponse("Bearer xx", null, "Bearer", null, null, null);
+ response.validate();
+ }
+
+ @Test
+ void testOAuthTokenException() throws IllegalArgumentException {
+ OAuth2TokenResponse response = new OAuth2TokenResponse();
+ assertThrows(IllegalArgumentException.class, () -> response.validate());
+ }
+
+ @Test
+ void testOAuthErrorResponse() throws IllegalArgumentException {
+ OAuth2ErrorResponse response = new OAuth2ErrorResponse("invalid_grant", "error");
+ response.validate(); // No exception thrown
+ }
+
+ @Test
+ void testOAuthErrorException() throws IllegalArgumentException {
+ OAuth2ErrorResponse response = new OAuth2ErrorResponse();
+ assertThrows(IllegalArgumentException.class, () -> response.validate());
+ }
}
diff --git a/common/src/test/java/com/datastrato/gravitino/json/TestJsonUtils.java b/common/src/test/java/com/datastrato/gravitino/json/TestJsonUtils.java
index 0452149ba2..af6104939e 100644
--- a/common/src/test/java/com/datastrato/gravitino/json/TestJsonUtils.java
+++ b/common/src/test/java/com/datastrato/gravitino/json/TestJsonUtils.java
@@ -147,4 +147,17 @@ public class TestJsonUtils {
+ "}";
Assertions.assertEquals(objectMapper.readTree(expected), objectMapper.readTree(jsonValue));
}
+
+ @Test
+ void testGetLong() throws Exception {
+ String jsonException = "{\"property\": \"value\"}";
+ JsonNode nodeException = objectMapper.readTree(jsonException);
+
+ Assertions.assertThrows(
+ IllegalArgumentException.class, () -> JsonUtils.getLong("property", nodeException));
+ String jsonNormal = "{\"property\": 1}";
+ JsonNode nodeNormal = objectMapper.readTree(jsonNormal);
+ Long result = JsonUtils.getLong("property", nodeNormal);
+ assertEquals(1L, result);
+ }
}
diff --git a/docs/security.md b/docs/security.md
index 0649c076b8..585a3e5600 100644
--- a/docs/security.md
+++ b/docs/security.md
@@ -12,11 +12,31 @@ Gravitino supports two kinds of authentication mechanism: simple and oauth.
Simple mode is the default authentication option.
Simple mode allows the client to use the environment variable `GRAVITINO_USER` as the user.
If the environment variable `GRAVITINO_USER` is not set, client will use the user of the machine which sends requests.
+For client side, users can enable `simple` mode by the code as below:
+```java
+GravitinoClient client = GravitinoClient.builder(uri)
+ .withSimpleAuth()
+ .build();
+```
### OAuth mode
-Gravitino only supports external OAuth2.0 server now.
+Gravitino only supports external OAuth 2.0 server now.
First, users need to guarantee that the external OAuth 2.0 server supports Bearer JWT and is configured properly.
Then, for server side, users should set `gravitino.authenticator` as `oauth` and give `gravitino.authenticator.oauth.defaultSignKey` a proper value.
+Next, for client side, users can enable `oauth` mode by the code as below:
+```java
+DefaultOAuth2TokenProvider authDataProvider = DefaultOAuth2TokenProvider.builder()
+ .withUri("oauth server uri")
+ .withCredential("yy:xx")
+ .withPath("oauth/token")
+ .withScope("test")
+ .build();
+
+GravitinoClient client = GravitinoClient.builder(uri)
+ .withOAuth(authDataProvider)
+ .build();
+```
+
### Server configuration
diff --git a/integration-test/src/main/java/com/datastrato/gravitino/integration/test/MiniGravitino.java b/integration-test/src/main/java/com/datastrato/gravitino/integration/test/MiniGravitino.java
index dc7a8578b5..341738eefc 100644
--- a/integration-test/src/main/java/com/datastrato/gravitino/integration/test/MiniGravitino.java
+++ b/integration-test/src/main/java/com/datastrato/gravitino/integration/test/MiniGravitino.java
@@ -8,7 +8,7 @@ import static com.datastrato.gravitino.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;
import com.datastrato.gravitino.Config;
import com.datastrato.gravitino.Configs;
-import com.datastrato.gravitino.auth.AuthConstants;
+import com.datastrato.gravitino.auth.AuthenticatorType;
import com.datastrato.gravitino.aux.AuxiliaryServiceManager;
import com.datastrato.gravitino.catalog.lakehouse.iceberg.IcebergRESTService;
import com.datastrato.gravitino.client.ErrorHandlers;
@@ -17,16 +17,18 @@ import com.datastrato.gravitino.client.RESTClient;
import com.datastrato.gravitino.dto.responses.VersionResponse;
import com.datastrato.gravitino.exceptions.RESTException;
import com.datastrato.gravitino.integration.test.util.ITUtils;
+import com.datastrato.gravitino.integration.test.util.OAuthMockDataProvider;
import com.datastrato.gravitino.rest.RESTUtils;
import com.datastrato.gravitino.server.GravitinoServer;
import com.datastrato.gravitino.server.ServerConfig;
+import com.datastrato.gravitino.server.auth.OAuthConfig;
import com.datastrato.gravitino.server.web.JettyServerConfig;
import com.google.common.collect.ImmutableMap;
-import com.google.common.collect.Maps;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
+import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
@@ -88,7 +90,18 @@ public class MiniGravitino {
this.host = jettyServerConfig.getHost();
this.port = jettyServerConfig.getHttpPort();
String URI = String.format("http://%s:%d", host, port);
- restClient = HTTPClient.builder(ImmutableMap.of()).uri(URI).build();
+ if (AuthenticatorType.OAUTH
+ .name()
+ .toLowerCase()
+ .equals(context.customConfig.get(OAuthConfig.AUTHENTICATOR.getKey()))) {
+ restClient =
+ HTTPClient.builder(ImmutableMap.of())
+ .uri(URI)
+ .withAuthDataProvider(OAuthMockDataProvider.getInstance())
+ .build();
+ } else {
+ restClient = HTTPClient.builder(ImmutableMap.of()).uri(URI).build();
+ }
Future<?> future =
executor.submit(
@@ -198,18 +211,14 @@ public class MiniGravitino {
String URI = String.format("http://%s:%d", host, port);
LOG.info("checkIfServerIsRunning() URI: {}", URI);
- restClient = HTTPClient.builder(ImmutableMap.of()).uri(URI).build();
- // TODO: We will refactor the test code after OAuth client's code is merged.
- String token = context.customConfig.get(AuthConstants.HTTP_HEADER_AUTHORIZATION);
- Map<String, String> headers = Maps.newHashMap();
- if (token != null) {
- headers.put(AuthConstants.HTTP_HEADER_AUTHORIZATION, token);
- }
VersionResponse response = null;
try {
response =
restClient.get(
- "api/version", VersionResponse.class, headers, ErrorHandlers.restErrorHandler());
+ "api/version",
+ VersionResponse.class,
+ Collections.emptyMap(),
+ ErrorHandlers.restErrorHandler());
} catch (RESTException e) {
LOG.warn("checkIfServerIsRunning() fails, GravitinoServer is not running");
}
diff --git a/integration-test/src/main/java/com/datastrato/gravitino/integration/test/util/OAuthMockDataProvider.java b/integration-test/src/main/java/com/datastrato/gravitino/integration/test/util/OAuthMockDataProvider.java
new file mode 100644
index 0000000000..378ae1735b
--- /dev/null
+++ b/integration-test/src/main/java/com/datastrato/gravitino/integration/test/util/OAuthMockDataProvider.java
@@ -0,0 +1,36 @@
+/*
+ * Copyright 2023 Datastrato.
+ * This software is licensed under the Apache License version 2.
+ */
+package com.datastrato.gravitino.integration.test.util;
+
+import com.datastrato.gravitino.client.OAuth2TokenProvider;
+import java.io.IOException;
+
+public class OAuthMockDataProvider extends OAuth2TokenProvider {
+
+ private static class InstanceHolder {
+ private static final OAuthMockDataProvider INSTANCE = new OAuthMockDataProvider();
+ }
+
+ @Override
+ protected String getAccessToken() {
+ return new String(token);
+ }
+
+ public static OAuthMockDataProvider getInstance() {
+ return OAuthMockDataProvider.InstanceHolder.INSTANCE;
+ }
+
+ private byte[] token;
+
+ /** Close the resource of OAuthTokenProvider */
+ @Override
+ public void close() throws IOException {
+ // no op
+ }
+
+ public void setTokenData(byte[] tokenData) {
+ this.token = tokenData;
+ }
+}
diff --git a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/AbstractIT.java b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/AbstractIT.java
index bb7eac2ae9..d5bb6f4c91 100644
--- a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/AbstractIT.java
+++ b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/util/AbstractIT.java
@@ -8,11 +8,13 @@ import static com.datastrato.gravitino.Configs.ENTRY_KV_ROCKSDB_BACKEND_PATH;
import static com.datastrato.gravitino.server.GravitinoServer.WEBSERVER_CONF_PREFIX;
import com.datastrato.gravitino.Config;
+import com.datastrato.gravitino.auth.AuthenticatorType;
import com.datastrato.gravitino.client.GravitinoClient;
import com.datastrato.gravitino.integration.test.MiniGravitino;
import com.datastrato.gravitino.integration.test.MiniGravitinoContext;
import com.datastrato.gravitino.server.GravitinoServer;
import com.datastrato.gravitino.server.ServerConfig;
+import com.datastrato.gravitino.server.auth.OAuthConfig;
import com.datastrato.gravitino.server.web.JettyServerConfig;
import java.io.File;
import java.io.IOException;
@@ -38,7 +40,10 @@ public class AbstractIT {
private static final Logger LOG = LoggerFactory.getLogger(AbstractIT.class);
protected static GravitinoClient client;
+ private static final OAuthMockDataProvider mockDataProvider = OAuthMockDataProvider.getInstance();
+
protected static final CloseableGroup closer = CloseableGroup.create();
+
private static MiniGravitino miniGravitino;
protected static Config serverConfig;
@@ -115,7 +120,14 @@ public class AbstractIT {
JettyServerConfig.fromConfig(serverConfig, WEBSERVER_CONF_PREFIX);
String uri = "http://" + jettyServerConfig.getHost() + ":" + jettyServerConfig.getHttpPort();
- client = GravitinoClient.builder(uri).build();
+ if (AuthenticatorType.OAUTH
+ .name()
+ .toLowerCase()
+ .equals(customConfigs.get(OAuthConfig.AUTHENTICATOR.getKey()))) {
+ client = GravitinoClient.builder(uri).withOAuth(mockDataProvider).build();
+ } else {
+ client = GravitinoClient.builder(uri).build();
+ }
}
@AfterAll
diff --git a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/web/rest/AuthenticationOperationsIT.java b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/web/rest/AuthenticationOperationsIT.java
index b6754218a0..5368d0bd83 100644
--- a/integration-test/src/test/java/com/datastrato/gravitino/integration/test/web/rest/AuthenticationOperationsIT.java
+++ b/integration-test/src/test/java/com/datastrato/gravitino/integration/test/web/rest/AuthenticationOperationsIT.java
@@ -4,25 +4,20 @@
*/
package com.datastrato.gravitino.integration.test.web.rest;
-import static com.datastrato.gravitino.server.GravitinoServer.WEBSERVER_CONF_PREFIX;
-
import com.datastrato.gravitino.auth.AuthConstants;
import com.datastrato.gravitino.auth.AuthenticatorType;
-import com.datastrato.gravitino.client.ErrorHandlers;
-import com.datastrato.gravitino.client.HTTPClient;
-import com.datastrato.gravitino.dto.responses.VersionResponse;
+import com.datastrato.gravitino.client.GravitinoVersion;
import com.datastrato.gravitino.integration.test.util.AbstractIT;
import com.datastrato.gravitino.integration.test.util.ITUtils;
-import com.datastrato.gravitino.json.JsonUtils;
+import com.datastrato.gravitino.integration.test.util.OAuthMockDataProvider;
import com.datastrato.gravitino.server.auth.OAuthConfig;
-import com.datastrato.gravitino.server.web.JettyServerConfig;
import com.google.common.collect.Maps;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.security.Keys;
+import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.util.Base64;
-import java.util.Collections;
import java.util.Date;
import java.util.Map;
import org.junit.jupiter.api.Assertions;
@@ -41,51 +36,31 @@ public class AuthenticationOperationsIT extends AbstractIT {
public static void startIntegrationTest() throws Exception {
Map<String, String> configs = Maps.newHashMap();
token =
- AuthConstants.AUTHORIZATION_BEARER_HEADER
- + Jwts.builder()
- .setSubject("gravitino")
- .setExpiration(new Date(System.currentTimeMillis() + 1000 * 1000))
- .setAudience("service1")
- .signWith(keyPair.getPrivate(), SignatureAlgorithm.RS256)
- .compact();
+ Jwts.builder()
+ .setSubject("gravitino")
+ .setExpiration(new Date(System.currentTimeMillis() + 1000 * 1000))
+ .setAudience("service1")
+ .signWith(keyPair.getPrivate(), SignatureAlgorithm.RS256)
+ .compact();
configs.put(OAuthConfig.AUTHENTICATOR.getKey(), AuthenticatorType.OAUTH.name().toLowerCase());
configs.put(OAuthConfig.SERVICE_AUDIENCE.getKey(), "service1");
configs.put(OAuthConfig.DEFAULT_SIGN_KEY.getKey(), publicKey);
configs.put(OAuthConfig.ALLOW_SKEW_SECONDS.getKey(), "6");
configs.put(AuthConstants.HTTP_HEADER_AUTHORIZATION, token);
registerCustomConfigs(configs);
+ OAuthMockDataProvider mockDataProvider = OAuthMockDataProvider.getInstance();
+ mockDataProvider.setTokenData(token.getBytes(StandardCharsets.UTF_8));
AbstractIT.startIntegrationTest();
}
@Test
public void testAuthenticationApi() throws Exception {
- JettyServerConfig jettyServerConfig =
- JettyServerConfig.fromConfig(serverConfig, WEBSERVER_CONF_PREFIX);
-
- String uri = "http://" + jettyServerConfig.getHost() + ":" + jettyServerConfig.getHttpPort();
-
- try (HTTPClient restClient =
- HTTPClient.builder(Collections.emptyMap())
- .uri(uri)
- .withObjectMapper(JsonUtils.objectMapper())
- .build(); ) {
- Map<String, String> headers = Maps.newHashMap();
- headers.put(AuthConstants.HTTP_HEADER_AUTHORIZATION, token);
- VersionResponse resp =
- restClient.get(
- "api/version", VersionResponse.class, headers, ErrorHandlers.restErrorHandler());
- resp.validate();
- String version = resp.getVersion().version();
- String compileDate = resp.getVersion().compileDate();
- String respGitCommit = resp.getVersion().gitCommit();
- Assertions.assertEquals(System.getenv("PROJECT_VERSION"), version);
- Assertions.assertFalse(compileDate.isEmpty());
-
- // Only in embedded will we have the git commit id.
- if (testMode.equals(ITUtils.EMBEDDED_TEST_MODE)) {
- final String gitCommitId = readGitCommitIdFromGitFile();
- Assertions.assertEquals(gitCommitId, respGitCommit);
- }
+ GravitinoVersion gravitinoVersion = client.getVersion();
+ Assertions.assertEquals(System.getenv("PROJECT_VERSION"), gravitinoVersion.version());
+ Assertions.assertFalse(gravitinoVersion.compileDate().isEmpty());
+ if (testMode.equals(ITUtils.EMBEDDED_TEST_MODE)) {
+ final String gitCommitId = readGitCommitIdFromGitFile();
+ Assertions.assertEquals(gitCommitId, gravitinoVersion.gitCommit());
}
}
}