World's most powerful open data catalog for building a high-performance, geo-distributed and federated metadata lake.
Java ai-catalogdata-catalogdatalakefederated-querylakehousemetadatametalakemodel-catalogopendatacatalogskycomputingstratosphere
[#12436] feat(client): support OAuth2 client_secret_basic authentication (#14886)
MaSai087d86b58a12
diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/DefaultOAuth2TokenProvider.java b/clients/client-java/src/main/java/org/apache/gravitino/client/DefaultOAuth2TokenProvider.javaindex 7d2e5fb870..ea234fb5c7 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/DefaultOAuth2TokenProvider.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/DefaultOAuth2TokenProvider.java@@ -29,6 +29,7 @@ public class DefaultOAuth2TokenProvider extends OAuth2TokenProvider {private String scope;private String path;private String token;+ private OAuth2ClientAuthenticationMethod authenticationMethod;private DefaultOAuth2TokenProvider() {}@@ -38,7 +39,8 @@ public class DefaultOAuth2TokenProvider extends OAuth2TokenProvider {Long expires = OAuth2ClientUtil.expiresAtMillis(token);if (expires == null || expires <= System.currentTimeMillis()) {token =- OAuth2ClientUtil.fetchToken(client, Collections.emptyMap(), credential, scope, path)+ OAuth2ClientUtil.fetchToken(+ client, Collections.emptyMap(), credential, scope, path, authenticationMethod).getAccessToken();}return token;@@ -61,6 +63,21 @@ public class DefaultOAuth2TokenProvider extends OAuth2TokenProvider {private String credential;private String scope;private String path;+ private OAuth2ClientAuthenticationMethod authenticationMethod =+ OAuth2ClientAuthenticationMethod.CLIENT_SECRET_POST;++ /**+ * Sets the OAuth2 client authentication method.+ *+ * @param authenticationMethod OAuth2 client authentication method.+ * @return This Builder instance.+ */+ public Builder withClientAuthenticationMethod(+ OAuth2ClientAuthenticationMethod authenticationMethod) {+ this.authenticationMethod =+ Preconditions.checkNotNull(authenticationMethod, "authenticationMethod cannot be null");+ return this;+ }/*** Sets the scope for the HTTP token requests.@@ -111,8 +128,10 @@ public class DefaultOAuth2TokenProvider extends OAuth2TokenProvider {provider.credential = credential;provider.scope = scope;provider.path = path;+ provider.authenticationMethod = authenticationMethod;provider.token =- OAuth2ClientUtil.fetchToken(client, Collections.emptyMap(), credential, scope, path)+ OAuth2ClientUtil.fetchToken(+ client, Collections.emptyMap(), credential, scope, path, authenticationMethod).getAccessToken();return provider;}diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/OAuth2ClientAuthenticationMethod.java b/clients/client-java/src/main/java/org/apache/gravitino/client/OAuth2ClientAuthenticationMethod.javanew file mode 100644index 0000000000..3039446ca6--- /dev/null+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/OAuth2ClientAuthenticationMethod.java@@ -0,0 +1,75 @@+/*+ * Licensed to the Apache Software Foundation (ASF) under one+ * or more contributor license agreements. See the NOTICE file+ * distributed with this work for additional information+ * regarding copyright ownership. The ASF licenses this file+ * to you under the Apache License, Version 2.0 (the+ * "License"); you may not use this file except in compliance+ * with the License. You may obtain a copy of the License at+ *+ * http://www.apache.org/licenses/LICENSE-2.0+ *+ * Unless required by applicable law or agreed to in writing,+ * software distributed under the License is distributed on an+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY+ * KIND, either express or implied. See the License for the+ * specific language governing permissions and limitations+ * under the License.+ */++package org.apache.gravitino.client;++import com.google.common.base.Preconditions;+import org.apache.commons.lang3.StringUtils;++/**+ * Authentication method used by the OAuth2 client-credentials flow.+ *+ * <p>Protocol names follow RFC 6749: {@code client_secret_post} and {@code client_secret_basic}.+ * Matching via {@link #fromValue(String)} is case-insensitive.+ */+public enum OAuth2ClientAuthenticationMethod {++ /** Client credentials are sent in the request body. */+ CLIENT_SECRET_POST("client_secret_post"),++ /** Client credentials are sent using HTTP Basic authentication. */+ CLIENT_SECRET_BASIC("client_secret_basic");++ private final String value;++ OAuth2ClientAuthenticationMethod(String value) {+ this.value = value;+ }++ /**+ * Returns the RFC-style protocol name for this method.+ *+ * @return {@code client_secret_post} or {@code client_secret_basic}+ */+ public String value() {+ return value;+ }++ /**+ * Parses an RFC-style OAuth2 client authentication method name.+ *+ * <p>Accepted values are {@code client_secret_post} and {@code client_secret_basic}+ * (case-insensitive).+ *+ * @param value the protocol name+ * @return the matching authentication method+ * @throws IllegalArgumentException if {@code value} is blank or unsupported+ */+ public static OAuth2ClientAuthenticationMethod fromValue(String value) {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(value), "OAuth2 client authentication method must not be blank");+ String normalized = value.trim();+ for (OAuth2ClientAuthenticationMethod method : values()) {+ if (method.value.equalsIgnoreCase(normalized)) {+ return method;+ }+ }+ throw new IllegalArgumentException("Unsupported OAuth2 client authentication method: " + value);+ }+}diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/OAuth2ClientUtil.java b/clients/client-java/src/main/java/org/apache/gravitino/client/OAuth2ClientUtil.javaindex 2b63afc89b..c81a93f34d 100644--- a/clients/client-java/src/main/java/org/apache/gravitino/client/OAuth2ClientUtil.java+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/OAuth2ClientUtil.java@@ -25,10 +25,15 @@ import com.google.common.base.Splitter;import com.google.common.collect.ImmutableList;import com.google.common.collect.ImmutableMap;import java.io.IOException;+import java.io.UnsupportedEncodingException;+import java.net.URLEncoder;+import java.nio.charset.StandardCharsets;import java.util.Base64;+import java.util.HashMap;import java.util.List;import java.util.Map;import java.util.concurrent.TimeUnit;+import org.apache.commons.lang3.StringUtils;import org.apache.commons.lang3.tuple.Pair;import org.apache.gravitino.dto.responses.OAuth2TokenResponse;import org.apache.gravitino.json.JsonUtils;@@ -60,19 +65,32 @@ class OAuth2ClientUtil {Map<String, String> headers,String credential,String scope,- String path) {- Map<String, String> request =- clientCredentialsRequest(- credential, scope != null ? ImmutableList.of(scope) : ImmutableList.of());+ String path,+ OAuth2ClientAuthenticationMethod authenticationMethod) {+ List<String> scopes = scope != null ? ImmutableList.of(scope) : ImmutableList.of();++ Pair<Map<String, String>, Map<String, String>> request =+ clientCredentialsRequest(credential, scopes, authenticationMethod);OAuth2TokenResponse response =client.postForm(- path, request, OAuth2TokenResponse.class, headers, ErrorHandlers.oauthErrorHandler());+ path,+ request.getLeft(),+ OAuth2TokenResponse.class,+ mergeHeaders(headers, request.getRight()),+ ErrorHandlers.oauthErrorHandler());response.validate();return response;}+ private static Map<String, String> mergeHeaders(+ Map<String, String> original, Map<String, String> additional) {+ Map<String, String> headers = new HashMap<>(original);+ headers.putAll(additional);+ return headers;+ }+private static Pair<String, String> parseCredential(String credential) {Preconditions.checkArgument(credential != null, "Invalid credential: null");List<String> parts = CREDENTIAL_SPLITTER.splitToList(credential);@@ -89,23 +107,68 @@ class OAuth2ClientUtil {}}- private static Map<String, String> clientCredentialsRequest(- String credential, List<String> scopes) {+ private static Pair<Map<String, String>, Map<String, String>> clientCredentialsRequest(+ String credential,+ List<String> scopes,+ OAuth2ClientAuthenticationMethod authenticationMethod) {+ Preconditions.checkNotNull(authenticationMethod, "authenticationMethod cannot be null");Pair<String, String> credentialPair = parseCredential(credential);- return clientCredentialsRequest(credentialPair.getLeft(), credentialPair.getRight(), scopes);++ switch (authenticationMethod) {+ case CLIENT_SECRET_BASIC:+ return buildClientSecretBasicRequest(credentialPair, scopes);+ case CLIENT_SECRET_POST:+ return buildClientCredentialRequest(credentialPair, scopes);+ default:+ throw new IllegalArgumentException(+ "Unsupported OAuth2 client authentication method: " + authenticationMethod);+ }+ }++ private static Pair<Map<String, String>, Map<String, String>> buildClientSecretBasicRequest(+ Pair<String, String> credentialPair, List<String> scopes) {+ Preconditions.checkArgument(+ StringUtils.isNotBlank(credentialPair.getLeft()),+ "Client ID is required for client_secret_basic authentication");++ String encodedClientId;+ String encodedClientSecret;+ try {+ encodedClientId = URLEncoder.encode(credentialPair.getLeft(), StandardCharsets.UTF_8.name());+ encodedClientSecret =+ URLEncoder.encode(credentialPair.getRight(), StandardCharsets.UTF_8.name());+ } catch (UnsupportedEncodingException e) {+ throw new IllegalStateException("UTF-8 encoding is unavailable", e);+ }++ String encoded =+ Base64.getEncoder()+ .encodeToString(+ (encodedClientId + ":" + encodedClientSecret).getBytes(StandardCharsets.UTF_8));++ Map<String, String> requestHeaders = new HashMap<>();+ requestHeaders.put("Authorization", "Basic " + encoded);++ Map<String, String> formData =+ ImmutableMap.<String, String>builder()+ .put(GRANT_TYPE, CLIENT_CREDENTIALS)+ .put(SCOPE, toScope(scopes))+ .build();++ return Pair.of(formData, requestHeaders);}- private static Map<String, String> clientCredentialsRequest(- String clientId, String clientSecret, List<String> scopes) {+ private static Pair<Map<String, String>, Map<String, String>> buildClientCredentialRequest(+ Pair<String, String> credentialPair, List<String> scopes) {ImmutableMap.Builder<String, String> formData = ImmutableMap.builder();formData.put(GRANT_TYPE, CLIENT_CREDENTIALS);- if (clientId != null) {- formData.put(CLIENT_ID, clientId);+ if (credentialPair.getLeft() != null) {+ formData.put(CLIENT_ID, credentialPair.getLeft());}- formData.put(CLIENT_SECRET, clientSecret);+ formData.put(CLIENT_SECRET, credentialPair.getRight());formData.put(SCOPE, toScope(scopes));- return formData.build();+ return Pair.of(formData.build(), ImmutableMap.of());}/**diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestOAuth2TokenProvider.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestOAuth2TokenProvider.javaindex 2c91f17e38..b0c63d67e3 100644--- a/clients/client-java/src/test/java/org/apache/gravitino/client/TestOAuth2TokenProvider.java+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestOAuth2TokenProvider.java@@ -29,6 +29,7 @@ import io.jsonwebtoken.security.Keys;import java.io.IOException;import java.nio.charset.StandardCharsets;import java.security.KeyPair;+import java.util.Base64;import java.util.Date;import org.apache.gravitino.auth.AuthConstants;import org.apache.gravitino.dto.responses.OAuth2ErrorResponse;@@ -42,6 +43,7 @@ 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.HttpRequest;import org.mockserver.model.HttpResponse;@SuppressWarnings("JavaUtilDate")@@ -184,4 +186,150 @@ public class TestOAuth2TokenProvider {String oldToken = provider.getAccessToken();Assertions.assertEquals(accessToken, oldToken);}++ @Test+ public void testClientSecretBasicAuthentication() throws Exception {+ OAuth2TokenProvider.Builder builder =+ DefaultOAuth2TokenProvider.builder()+ .withUri(String.format("http://127.0.0.1:%d", PORT))+ .withCredential("clientId:clientSecret")+ .withPath("oauth/token")+ .withScope("test")+ .withClientAuthenticationMethod(OAuth2ClientAuthenticationMethod.CLIENT_SECRET_BASIC);++ OAuth2TokenResponse response =+ new OAuth2TokenResponse("access-token", "refresh-token", "bearer", 3600, "test", null);+ String respJson = ObjectMapperProvider.objectMapper().writeValueAsString(response);++ String basicAuth =+ "Basic "+ + Base64.getEncoder()+ .encodeToString("clientId:clientSecret".getBytes(StandardCharsets.UTF_8));++ HttpRequest tokenRequest = HttpRequest.request().withMethod("POST").withPath("/oauth/token");++ mockServer.clear(tokenRequest);++ HttpResponse mockResponse =+ HttpResponse.response().withStatusCode(HttpStatus.SC_OK).withBody(respJson);++ mockServer+ .when(+ HttpRequest.request()+ .withMethod("POST")+ .withPath("/oauth/token")+ .withHeader("Authorization", basicAuth),+ Times.exactly(2))+ .respond(mockResponse);++ OAuth2TokenProvider provider = builder.build();++ Assertions.assertTrue(provider.hasTokenData());+ Assertions.assertEquals(+ AuthConstants.AUTHORIZATION_BEARER_HEADER + "access-token",+ new String(provider.getTokenData(), StandardCharsets.UTF_8));++ HttpRequest[] recordedRequests = mockServer.retrieveRecordedRequests(tokenRequest);+ Assertions.assertEquals(2, recordedRequests.length);++ for (HttpRequest recordedRequest : recordedRequests) {+ Assertions.assertEquals(basicAuth, recordedRequest.getFirstHeader("Authorization"));++ String requestBody = recordedRequest.getBodyAsString();+ Assertions.assertFalse(requestBody.contains("client_id"));+ Assertions.assertFalse(requestBody.contains("client_secret"));+ }+ }++ @Test+ public void testClientSecretBasicRequiresClientId() {+ OAuth2TokenProvider.Builder builder =+ DefaultOAuth2TokenProvider.builder()+ .withUri(String.format("http://127.0.0.1:%d", PORT))+ .withCredential("clientSecret")+ .withPath("oauth/token")+ .withScope("test")+ .withClientAuthenticationMethod(OAuth2ClientAuthenticationMethod.CLIENT_SECRET_BASIC);++ Assertions.assertThrows(IllegalArgumentException.class, builder::build);+ }++ @Test+ public void testRejectsNullClientAuthenticationMethod() {+ DefaultOAuth2TokenProvider.Builder builder =+ DefaultOAuth2TokenProvider.builder()+ .withUri(String.format("http://127.0.0.1:%d", PORT))+ .withCredential("clientId:clientSecret")+ .withPath("oauth/token")+ .withScope("test");++ Assertions.assertThrows(+ NullPointerException.class, () -> builder.withClientAuthenticationMethod(null));+ }++ @Test+ public void testFromValueAcceptsRfcStyleNames() {+ Assertions.assertEquals(+ OAuth2ClientAuthenticationMethod.CLIENT_SECRET_BASIC,+ OAuth2ClientAuthenticationMethod.fromValue("client_secret_basic"));+ Assertions.assertEquals(+ OAuth2ClientAuthenticationMethod.CLIENT_SECRET_BASIC,+ OAuth2ClientAuthenticationMethod.fromValue("CLIENT_SECRET_BASIC"));+ Assertions.assertEquals(+ OAuth2ClientAuthenticationMethod.CLIENT_SECRET_POST,+ OAuth2ClientAuthenticationMethod.fromValue("client_secret_post"));+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> OAuth2ClientAuthenticationMethod.fromValue("basic"));+ Assertions.assertThrows(+ IllegalArgumentException.class, () -> OAuth2ClientAuthenticationMethod.fromValue(""));+ }++ @Test+ public void testClientSecretBasicEncodesReservedCharacters() throws Exception {+ OAuth2TokenProvider.Builder builder =+ DefaultOAuth2TokenProvider.builder()+ .withUri(String.format("http://127.0.0.1:%d", PORT))+ .withCredential("client*@id:s ecret:/+?~")+ .withPath("oauth/token")+ .withScope("test")+ .withClientAuthenticationMethod(OAuth2ClientAuthenticationMethod.CLIENT_SECRET_BASIC);++ OAuth2TokenResponse response =+ new OAuth2TokenResponse("access-token", "refresh-token", "bearer", 3600, "test", null);+ String respJson = ObjectMapperProvider.objectMapper().writeValueAsString(response);++ String basicAuth = "Basic Y2xpZW50KiU0MGlkOnMrZWNyZXQlM0ElMkYlMkIlM0YlN0U=";++ HttpRequest tokenRequest = HttpRequest.request().withMethod("POST").withPath("/oauth/token");+ mockServer.clear(tokenRequest);++ HttpResponse mockResponse =+ HttpResponse.response().withStatusCode(HttpStatus.SC_OK).withBody(respJson);++ mockServer+ .when(+ HttpRequest.request()+ .withMethod("POST")+ .withPath("/oauth/token")+ .withHeader("Authorization", basicAuth),+ Times.exactly(2))+ .respond(mockResponse);++ OAuth2TokenProvider provider = builder.build();++ Assertions.assertTrue(provider.hasTokenData());+ Assertions.assertEquals(+ AuthConstants.AUTHORIZATION_BEARER_HEADER + "access-token",+ new String(provider.getTokenData(), StandardCharsets.UTF_8));+ HttpRequest[] recordedRequests = mockServer.retrieveRecordedRequests(tokenRequest);+ Assertions.assertEquals(2, recordedRequests.length);++ for (HttpRequest recordedRequest : recordedRequests) {+ Assertions.assertEquals(basicAuth, recordedRequest.getFirstHeader("Authorization"));++ String requestBody = recordedRequest.getBodyAsString();+ Assertions.assertFalse(requestBody.contains("client_id"));+ Assertions.assertFalse(requestBody.contains("client_secret"));+ }+ }}diff --git a/clients/client-python/gravitino/auth/default_oauth2_token_provider.py b/clients/client-python/gravitino/auth/default_oauth2_token_provider.pyindex 8b3fa4937d..92c77b6787 100644--- a/clients/client-python/gravitino/auth/default_oauth2_token_provider.py+++ b/clients/client-python/gravitino/auth/default_oauth2_token_provider.py@@ -15,15 +15,20 @@# specific language governing permissions and limitations# under the License.-import time-import jsonimport base64+import json+import timefrom typing import Optional+from urllib.parse import quote_plus++from gravitino.auth.oauth2_client_authentication_method import (+ OAuth2ClientAuthenticationMethod,+)from gravitino.auth.oauth2_token_provider import OAuth2TokenProvider-from gravitino.dto.responses.oauth2_token_response import OAuth2TokenResponsefrom gravitino.dto.requests.oauth2_client_credential_request import (OAuth2ClientCredentialRequest,)+from gravitino.dto.responses.oauth2_token_response import OAuth2TokenResponsefrom gravitino.exceptions.base import (GravitinoRuntimeException,IllegalArgumentException,@@ -43,6 +48,7 @@ class DefaultOAuth2TokenProvider(OAuth2TokenProvider):_scope: Optional[str]_path: Optional[str]_token: Optional[str]+ _authentication_method: OAuth2ClientAuthenticationMethoddef __init__(self,@@ -50,13 +56,15 @@ class DefaultOAuth2TokenProvider(OAuth2TokenProvider):credential: str = None,scope: str = None,path: str = None,+ *,+ authentication_method: OAuth2ClientAuthenticationMethod = OAuth2ClientAuthenticationMethod.CLIENT_SECRET_POST,):super().__init__(uri)self._credential = credentialself._scope = scopeself._path = path-+ self._authentication_method = authentication_methodself.validate()self._token = self._fetch_token()@@ -103,16 +111,47 @@ class DefaultOAuth2TokenProvider(OAuth2TokenProvider):def _fetch_token(self) -> str:client_id, client_secret = self._parse_credential()- client_credential_request = OAuth2ClientCredentialRequest(- grant_type=CLIENT_CREDENTIALS,- client_id=client_id,- client_secret=client_secret,- scope=self._scope,- )+ headers = {}++ if (+ self._authentication_method+ == OAuth2ClientAuthenticationMethod.CLIENT_SECRET_BASIC+ ):+ if not client_id or not client_id.strip():+ raise IllegalArgumentException(+ "client_id must be set when using client_secret_basic authentication"+ )++ encoded_client_id = quote_plus(client_id, safe="*").replace("~", "%7E")+ encoded_client_secret = quote_plus(client_secret, safe="*").replace(+ "~", "%7E"+ )+ credentials = f"{encoded_client_id}:{encoded_client_secret}"+ encoded_credentials = base64.b64encode(credentials.encode("utf-8")).decode(+ "utf-8"+ )++ headers["Authorization"] = f"Basic {encoded_credentials}"++ client_credential_request = OAuth2ClientCredentialRequest(+ grant_type=CLIENT_CREDENTIALS,+ client_id=None,+ client_secret=None,+ scope=self._scope,+ )++ else:+ client_credential_request = OAuth2ClientCredentialRequest(+ grant_type=CLIENT_CREDENTIALS,+ client_id=client_id,+ client_secret=client_secret,+ scope=self._scope,+ )resp = self._client.post_form(self._path,data=client_credential_request,+ headers=headers,error_handler=OAUTH_ERROR_HANDLER,)oauth2_resp = OAuth2TokenResponse.from_json(resp.body, infer_missing=True)diff --git a/clients/client-python/gravitino/auth/oauth2_client_authentication_method.py b/clients/client-python/gravitino/auth/oauth2_client_authentication_method.pynew file mode 100644index 0000000000..84bfa9a3b0--- /dev/null+++ b/clients/client-python/gravitino/auth/oauth2_client_authentication_method.py@@ -0,0 +1,50 @@+# 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.+++from enum import Enum+from typing import Union+++class OAuth2ClientAuthenticationMethod(Enum):+ """OAuth2 client authentication method for the client-credentials flow.++ Protocol names follow RFC 6749: ``client_secret_post`` and+ ``client_secret_basic``. Matching via ``from_value`` is case-insensitive.+ """++ CLIENT_SECRET_POST = "client_secret_post"+ CLIENT_SECRET_BASIC = "client_secret_basic"++ @classmethod+ def from_value(+ cls, value: Union[str, "OAuth2ClientAuthenticationMethod"]+ ) -> "OAuth2ClientAuthenticationMethod":+ """Parse an RFC-style OAuth2 client authentication method name.++ Accepted values are ``client_secret_post`` and ``client_secret_basic``+ (case-insensitive).+ """+ if isinstance(value, cls):+ return value+ if value is None or not str(value).strip():+ raise ValueError("OAuth2 client authentication method must not be blank")+ normalized = str(value).strip().lower()+ for method in cls:+ if method.value == normalized:+ return method+ raise ValueError(f"Unsupported OAuth2 client authentication method: {value}")diff --git a/clients/client-python/gravitino/filesystem/gvfs_config.py b/clients/client-python/gravitino/filesystem/gvfs_config.pyindex f6c46f7741..6233d59e92 100644--- a/clients/client-python/gravitino/filesystem/gvfs_config.py+++ b/clients/client-python/gravitino/filesystem/gvfs_config.py@@ -34,6 +34,7 @@ class GVFSConfig:OAUTH2_CREDENTIAL = "oauth2_credential"OAUTH2_PATH = "oauth2_path"OAUTH2_SCOPE = "oauth2_scope"+ OAUTH2_CLIENT_AUTHENTICATION_METHOD = "oauth2_client_authentication_method"GVFS_FILESYSTEM_GCS_SERVICE_KEY_FILE = "gcs_service_account_file"diff --git a/clients/client-python/gravitino/filesystem/gvfs_utils.py b/clients/client-python/gravitino/filesystem/gvfs_utils.pyindex 9c3ef17257..84ba2898a4 100644--- a/clients/client-python/gravitino/filesystem/gvfs_utils.py+++ b/clients/client-python/gravitino/filesystem/gvfs_utils.py@@ -17,14 +17,17 @@import refrom typing import Dict-from gravitino.client.gravitino_client import GravitinoClientfrom gravitino.auth.basic_auth_provider import BasicAuthProviderfrom gravitino.auth.default_oauth2_token_provider import DefaultOAuth2TokenProvider+from gravitino.auth.oauth2_client_authentication_method import (+ OAuth2ClientAuthenticationMethod,+)from gravitino.auth.oauth2_token_provider import OAuth2TokenProviderfrom gravitino.auth.simple_auth_provider import SimpleAuthProvider+from gravitino.client.gravitino_client import GravitinoClient+from gravitino.exceptions.base import GravitinoRuntimeExceptionfrom gravitino.filesystem.gvfs_config import GVFSConfigfrom gravitino.name_identifier import NameIdentifier-from gravitino.exceptions.base import GravitinoRuntimeException_identifier_pattern = re.compile("^(?:gvfs://)?fileset/([^/]+)/([^/]+)/([^/]+)(?:/[^/]+)*/?$"@@ -44,6 +47,46 @@ def _check_auth_config(auth_type: str, config_key: str, config_value: str):)+def _create_oauth2_token_provider(options: Dict[str, str]) -> OAuth2TokenProvider:+ """Build an OAuth2 token provider from GVFS options."""+ auth_type = GVFSConfig.OAUTH2_AUTH_TYPE++ oauth2_server_uri = options.get(GVFSConfig.OAUTH2_SERVER_URI)+ _check_auth_config(auth_type, GVFSConfig.OAUTH2_SERVER_URI, oauth2_server_uri)++ oauth2_credential = options.get(GVFSConfig.OAUTH2_CREDENTIAL)+ _check_auth_config(auth_type, GVFSConfig.OAUTH2_CREDENTIAL, oauth2_credential)++ oauth2_path = options.get(GVFSConfig.OAUTH2_PATH)+ _check_auth_config(auth_type, GVFSConfig.OAUTH2_PATH, oauth2_path)++ oauth2_scope = options.get(GVFSConfig.OAUTH2_SCOPE)+ _check_auth_config(auth_type, GVFSConfig.OAUTH2_SCOPE, oauth2_scope)++ authentication_method_value = options.get(+ GVFSConfig.OAUTH2_CLIENT_AUTHENTICATION_METHOD,+ OAuth2ClientAuthenticationMethod.CLIENT_SECRET_POST.value,+ )++ try:+ authentication_method = OAuth2ClientAuthenticationMethod.from_value(+ authentication_method_value+ )+ except ValueError as exc:+ raise GravitinoRuntimeException(+ f"Unsupported OAuth2 client authentication method: "+ f"{authentication_method_value}"+ ) from exc++ return DefaultOAuth2TokenProvider(+ uri=oauth2_server_uri,+ credential=oauth2_credential,+ scope=oauth2_scope,+ path=oauth2_path,+ authentication_method=authentication_method,+ )++def create_client(options: Dict[str, str],server_uri: str,@@ -90,26 +133,10 @@ def create_client()if auth_type == GVFSConfig.OAUTH2_AUTH_TYPE:- oauth2_server_uri = options.get(GVFSConfig.OAUTH2_SERVER_URI)- _check_auth_config(auth_type, GVFSConfig.OAUTH2_SERVER_URI, oauth2_server_uri)-- oauth2_credential = options.get(GVFSConfig.OAUTH2_CREDENTIAL)- _check_auth_config(auth_type, GVFSConfig.OAUTH2_CREDENTIAL, oauth2_credential)-- oauth2_path = options.get(GVFSConfig.OAUTH2_PATH)- _check_auth_config(auth_type, GVFSConfig.OAUTH2_PATH, oauth2_path)-- oauth2_scope = options.get(GVFSConfig.OAUTH2_SCOPE)- _check_auth_config(auth_type, GVFSConfig.OAUTH2_SCOPE, oauth2_scope)-- oauth2_token_provider: OAuth2TokenProvider = DefaultOAuth2TokenProvider(- oauth2_server_uri, oauth2_credential, oauth2_path, oauth2_scope- )-return GravitinoClient(uri=server_uri,metalake_name=metalake_name,- auth_data_provider=oauth2_token_provider,+ auth_data_provider=_create_oauth2_token_provider(options),request_headers=request_headers,client_config=client_config,)diff --git a/clients/client-python/tests/unittests/auth/mock_base.py b/clients/client-python/tests/unittests/auth/mock_base.pyindex ea37668d1c..52410dbbe7 100644--- a/clients/client-python/tests/unittests/auth/mock_base.py+++ b/clients/client-python/tests/unittests/auth/mock_base.py@@ -15,16 +15,16 @@# specific language governing permissions and limitations# under the License.-import timeimport json+import timefrom dataclasses import dataclassfrom http import HTTPStatus-from dataclasses_json import dataclass_jsonimport jwt+from cryptography.hazmat.backends import default_backend as crypto_default_backendfrom cryptography.hazmat.primitives import serialization as crypto_serializationfrom cryptography.hazmat.primitives.asymmetric import rsa-from cryptography.hazmat.backends import default_backend as crypto_default_backend+from dataclasses_json import dataclass_jsonfrom gravitino.dto.responses.oauth2_error_response import OAuth2ErrorResponsefrom gravitino.exceptions.handlers.oauth_error_handler import (@@ -166,3 +166,22 @@ def mock_authentication_with_jwt():status_code=HTTPStatus.OK.value,),]+++def mock_authentication_with_basic_jwt():+ _, new_access_token = mock_old_new_jwt()++ return TestResponse(+ body=json.dumps(+ {+ "code": 0,+ "access_token": new_access_token,+ "issued_token_type": "2",+ "token_type": "bearer",+ "expires_in": 3600,+ "scope": "test",+ "refresh_token": None,+ }+ ),+ status_code=HTTPStatus.OK.value,+ )diff --git a/clients/client-python/tests/unittests/auth/test_oauth2_token_provider.py b/clients/client-python/tests/unittests/auth/test_oauth2_token_provider.pyindex ddf998c011..532a2d7531 100644--- a/clients/client-python/tests/unittests/auth/test_oauth2_token_provider.py+++ b/clients/client-python/tests/unittests/auth/test_oauth2_token_provider.py@@ -20,6 +20,9 @@ from unittest.mock import patchfrom gravitino.auth.auth_constants import AuthConstantsfrom gravitino.auth.default_oauth2_token_provider import DefaultOAuth2TokenProvider+from gravitino.auth.oauth2_client_authentication_method import (+ OAuth2ClientAuthenticationMethod,+)from gravitino.auth.oauth2_token_provider import OAuth2TokenProviderfrom gravitino.exceptions.base import (BadRequestException,@@ -137,3 +140,80 @@ class TestOAuth2TokenProvider(unittest.TestCase):token_provider.get_token_data().decode("utf-8"),AuthConstants.AUTHORIZATION_BEARER_HEADER + new_access_token,)++ @patch(+ "gravitino.utils.http_client.HTTPClient.post_form",+ return_value=mock_base.mock_authentication_with_basic_jwt(),+ )+ def test_client_secret_basic_authentication(self, mock_post_form):+ token_provider = DefaultOAuth2TokenProvider(+ uri=f"http://127.0.0.1:{OAUTH_PORT}",+ credential="clientId:clientSecret",+ path="oauth/token",+ scope="test",+ authentication_method=(+ OAuth2ClientAuthenticationMethod.CLIENT_SECRET_BASIC+ ),+ )++ self.assertTrue(token_provider.has_token_data())+ _, kwargs = mock_post_form.call_args+ self.assertIsNone(kwargs["data"].client_id)+ self.assertIsNone(kwargs["data"].client_secret)++ self.assertEqual(+ kwargs["headers"]["Authorization"],+ "Basic Y2xpZW50SWQ6Y2xpZW50U2VjcmV0",+ )++ def test_client_secret_basic_requires_client_id(self):+ with self.assertRaises(IllegalArgumentException):+ DefaultOAuth2TokenProvider(+ uri=f"http://127.0.0.1:{OAUTH_PORT}",+ credential=":clientSecret",+ path="oauth/token",+ scope="test",+ authentication_method=(+ OAuth2ClientAuthenticationMethod.CLIENT_SECRET_BASIC+ ),+ )++ def test_from_value_accepts_rfc_style_names(self):+ self.assertEqual(+ OAuth2ClientAuthenticationMethod.CLIENT_SECRET_BASIC,+ OAuth2ClientAuthenticationMethod.from_value("client_secret_basic"),+ )+ self.assertEqual(+ OAuth2ClientAuthenticationMethod.CLIENT_SECRET_BASIC,+ OAuth2ClientAuthenticationMethod.from_value("CLIENT_SECRET_BASIC"),+ )+ self.assertEqual(+ OAuth2ClientAuthenticationMethod.CLIENT_SECRET_POST,+ OAuth2ClientAuthenticationMethod.from_value("client_secret_post"),+ )+ with self.assertRaises(ValueError):+ OAuth2ClientAuthenticationMethod.from_value("basic")+ with self.assertRaises(ValueError):+ OAuth2ClientAuthenticationMethod.from_value("")++ @patch(+ "gravitino.utils.http_client.HTTPClient.post_form",+ return_value=mock_base.mock_authentication_with_basic_jwt(),+ )+ def test_client_secret_basic_encodes_reserved_characters(self, mock_post_form):+ DefaultOAuth2TokenProvider(+ uri=f"http://127.0.0.1:{OAUTH_PORT}",+ credential="client*@id:s ecret:/+?~",+ path="oauth/token",+ scope="test",+ authentication_method=(+ OAuth2ClientAuthenticationMethod.CLIENT_SECRET_BASIC+ ),+ )++ _, kwargs = mock_post_form.call_args++ self.assertEqual(+ kwargs["headers"]["Authorization"],+ "Basic Y2xpZW50KiU0MGlkOnMrZWNyZXQlM0ElMkYlMkIlM0YlN0U=",+ )diff --git a/clients/client-python/tests/unittests/test_gvfs_with_local.py b/clients/client-python/tests/unittests/test_gvfs_with_local.pyindex b7a3a18566..4c882aab0e 100644--- a/clients/client-python/tests/unittests/test_gvfs_with_local.py+++ b/clients/client-python/tests/unittests/test_gvfs_with_local.py@@ -32,6 +32,9 @@ from fsspec.implementations.local import LocalFileSystemfrom gravitino import gvfs, NameIdentifierfrom gravitino.auth.auth_constants import AuthConstants+from gravitino.auth.oauth2_client_authentication_method import (+ OAuth2ClientAuthenticationMethod,+)from gravitino.constants.timeout import TIMEOUTfrom gravitino.exceptions.base import (GravitinoRuntimeException,@@ -1481,3 +1484,41 @@ class TestLocalFilesystem(unittest.TestCase):fs_default._operations._auto_create_location,"auto_create_location should default to True",)++ def test_oauth2_client_authentication_method(self, *mock_methods):+ for method_value in (+ OAuth2ClientAuthenticationMethod.CLIENT_SECRET_BASIC.value,+ "CLIENT_SECRET_BASIC",+ ):+ options = {+ GVFSConfig.AUTH_TYPE: GVFSConfig.OAUTH2_AUTH_TYPE,+ GVFSConfig.OAUTH2_SERVER_URI: "http://127.0.0.1:1082",+ GVFSConfig.OAUTH2_CREDENTIAL: "client_id:client_secret",+ GVFSConfig.OAUTH2_SCOPE: "test",+ GVFSConfig.OAUTH2_PATH: "token/test",+ GVFSConfig.OAUTH2_CLIENT_AUTHENTICATION_METHOD: method_value,+ }++ mocked_jwt = mock_jwt(+ sub="gravitino", exp=GENERATED_TIME + 10000, aud="service1"+ )++ with patch(+ "gravitino.auth.default_oauth2_token_provider.DefaultOAuth2TokenProvider._fetch_token",+ return_value=mocked_jwt,+ ):+ fs = gvfs.GravitinoVirtualFileSystem(+ server_uri=self._server_uri,+ metalake_name=self._metalake_name,+ options=options,+ skip_instance_cache=True,+ )++ client = fs._operations._get_gravitino_client()+ provider = client._rest_client.auth_data_provider++ self.assertEqual(+ OAuth2ClientAuthenticationMethod.CLIENT_SECRET_BASIC,+ provider._authentication_method,+ method_value,+ )diff --git a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/GravitinoVirtualFileSystemConfiguration.java b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/GravitinoVirtualFileSystemConfiguration.javaindex 2cc8dd0e49..7be8dd0ad1 100644--- a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/GravitinoVirtualFileSystemConfiguration.java+++ b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/GravitinoVirtualFileSystemConfiguration.java@@ -89,6 +89,15 @@ public class GravitinoVirtualFileSystemConfiguration {public static final String FS_GRAVITINO_CLIENT_OAUTH2_SCOPE_KEY ="fs.gravitino.client.oauth2.scope";+ /**+ * The configuration key for the OAuth2 client authentication method.+ *+ * <p>Canonical values are the RFC 6749 style names {@code client_secret_post} (default) and+ * {@code client_secret_basic} (case-insensitive).+ */+ public static final String FS_GRAVITINO_CLIENT_OAUTH2_AUTHENTICATION_METHOD_KEY =+ "fs.gravitino.client.oauth2.authenticationMethod";+/** The configuration key prefix for kerberos */public static final String FS_GRAVITINO_CLIENT_KERBEROS_PREFIX = "fs.gravitino.client.kerberos.";diff --git a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/GravitinoVirtualFileSystemUtils.java b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/GravitinoVirtualFileSystemUtils.javaindex aca5b3ce9f..790954184f 100644--- a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/GravitinoVirtualFileSystemUtils.java+++ b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/GravitinoVirtualFileSystemUtils.java@@ -41,6 +41,7 @@ import org.apache.gravitino.audit.CallerContext;import org.apache.gravitino.client.DefaultOAuth2TokenProvider;import org.apache.gravitino.client.GravitinoClient;import org.apache.gravitino.client.KerberosTokenProvider;+import org.apache.gravitino.client.OAuth2ClientAuthenticationMethod;import org.apache.gravitino.credential.CredentialConstants;import org.apache.hadoop.conf.Configuration;@@ -196,12 +197,22 @@ public class GravitinoVirtualFileSystemUtils {GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_OAUTH2_SCOPE_KEY,scope);+ String authenticationMethodValue =+ configuration.getOrDefault(+ GravitinoVirtualFileSystemConfiguration+ .FS_GRAVITINO_CLIENT_OAUTH2_AUTHENTICATION_METHOD_KEY,+ "client_secret_post");++ OAuth2ClientAuthenticationMethod authenticationMethod =+ OAuth2ClientAuthenticationMethod.fromValue(authenticationMethodValue);+DefaultOAuth2TokenProvider authDataProvider =DefaultOAuth2TokenProvider.builder().withUri(authServerUri).withCredential(credential).withPath(path).withScope(scope)+ .withClientAuthenticationMethod(authenticationMethod).build();return GravitinoClient.builder(serverUri)diff --git a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestOauth2Client.java b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestOauth2Client.javaindex e673e1e1b0..21a5f582ed 100644--- a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestOauth2Client.java+++ b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestOauth2Client.java@@ -65,6 +65,7 @@ import org.junit.jupiter.api.AfterAll;import org.junit.jupiter.api.BeforeAll;import org.junit.jupiter.api.Test;import org.mockserver.matchers.Times;+import org.mockserver.model.ClearType;import org.mockserver.model.Header;import org.mockserver.model.HttpRequest;import org.mockserver.model.HttpResponse;@@ -403,4 +404,53 @@ public class TestOauth2Client extends TestGvfsBase {fs.exists(managedFilesetPath);});}++ @Test+ public void testFileSystemClientSecretBasicAuthentication() {+ Map<String, String> configuration = new HashMap<>();+ configuration.put(+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_SERVER_URI_KEY, serverUri());+ configuration.put(+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_METALAKE_KEY, metalakeName);+ configuration.put(+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_AUTH_TYPE_KEY,+ GravitinoVirtualFileSystemConfiguration.OAUTH2_AUTH_TYPE);+ configuration.put(+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_OAUTH2_SERVER_URI_KEY,+ Oauth2MockServerBase.serverUri());+ configuration.put(+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_OAUTH2_CREDENTIAL_KEY,+ credential);+ configuration.put(+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_OAUTH2_PATH_KEY, normal_path);+ configuration.put(+ GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_OAUTH2_SCOPE_KEY, scope);+ configuration.put(+ GravitinoVirtualFileSystemConfiguration+ .FS_GRAVITINO_CLIENT_OAUTH2_AUTHENTICATION_METHOD_KEY,+ "client_secret_basic");++ HttpRequest tokenRequest = request().withMethod("POST").withPath("/" + normal_path);+ Oauth2MockServerBase.mockServer().clear(tokenRequest, ClearType.LOG);++ GravitinoVirtualFileSystemUtils.createClient(configuration);++ String expectedAuthorization =+ "Basic " + Base64.getEncoder().encodeToString(credential.getBytes(StandardCharsets.UTF_8));++ HttpRequest[] recordedRequests =+ Oauth2MockServerBase.mockServer().retrieveRecordedRequests(tokenRequest);++ boolean basicAuthenticationFound = false;+ for (HttpRequest recordedRequest : recordedRequests) {+ if (expectedAuthorization.equals(recordedRequest.getFirstHeader("Authorization"))) {+ basicAuthenticationFound = true;+ break;+ }+ }++ assertTrue(+ basicAuthenticationFound,+ "OAuth2 token request should use HTTP Basic client authentication");+ }}diff --git a/docs/security/how-to-authenticate.md b/docs/security/how-to-authenticate.mdindex 28b273a875..2b4177b263 100644--- a/docs/security/how-to-authenticate.md+++ b/docs/security/how-to-authenticate.md@@ -132,6 +132,34 @@ GravitinoClient client = GravitinoClient.builder(uri).build();```+#### OAuth2 Client Authentication Method++By default, the Java OAuth2 token provider uses `client_secret_post`, which sends the client credentials in the request body. To use HTTP Basic authentication, configure the provider with `OAuth2ClientAuthenticationMethod.CLIENT_SECRET_BASIC`:++```java+DefaultOAuth2TokenProvider authDataProvider = DefaultOAuth2TokenProvider.builder()+ .withUri("oauth server uri")+ .withCredential("yy:xx")+ .withPath("oauth/token")+ .withScope("test")+ .withClientAuthenticationMethod(+ OAuth2ClientAuthenticationMethod.CLIENT_SECRET_BASIC)+ .build();+```++The Java GVFS Hadoop integration supports the configuration property `fs.gravitino.client.oauth2.authenticationMethod`, with `client_secret_post` as the default. The Python GVFS integration supports `oauth2_client_authentication_method`, also defaulting to `client_secret_post`.++Canonical config values are the RFC 6749 style strings `client_secret_post` and `client_secret_basic` (case-insensitive) on both Java and Python GVFS.++**Current limitation:** Several built-in OAuth2 bootstrap paths do not yet expose a configuration option for selecting the client authentication method and continue to use `client_secret_post`, including:++- Spark, Flink, and Trino connectors+- Java CLI (`Command`)+- Lance namespace wrapper+- Iceberg `DynamicIcebergConfigProvider`+- Maintenance optimizer `GravitinoAuthSettings`++### Kerberos ModeTo enable Kerberos mode, users must ensure that the server and client have the correct Kerberos configuration. On the server side, users should set `gravitino.authenticators` as `kerberos` and give