This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/gravitino.git
The following commit(s) were added to refs/heads/main by this push:
new 922ed72173 [#14638] fix(jdbc): protect catalog credentials and reject
URL secrets (#14639)
922ed72173 is described below
commit 922ed72173d9f153286a9cf30c5fc9c716c4520c
Author: Qi Yu <[email protected]>
AuthorDate: Thu Nov 5 17:43:30 2026 +0800
[#14638] fix(jdbc): protect catalog credentials and reject URL secrets
(#14639)
### What changes were proposed in this pull request?
- Require both USE_SECRETS and INCLUDE_CREDENTIAL_SECRETS (or metalake
ownership), in addition to metadata access, for catalog-level credential
vending. Leave fileset path authorization unchanged; Java/Python GVFS
skip a forbidden optional catalog-credential overlay and continue to
fileset vending, while fileset denial still blocks access.
- Reject relational JDBC catalogs' `jdbc-url` values containing
credential parameters or inline user information, including encoded
parameter names and encoded inline passwords; inspect raw authority
before decoding URL delimiters. Preserve the non-secret Connector/J
options `passwordCharacterEncoding` and `disconnectOnExpiredPasswords`
across standard and DNS SRV URL families. Mask legacy credential-bearing
URLs on the property read path; log class-loader property names without
values.
- Return a client error for unsupported credential object types,
preserve the requested object name, and map credential refusals to 403.
### Why are the changes needed?
Catalog-level credentials are authorized as metadata reads, so a
principal with USE_CATALOG can recover the source account's password and
bypass table-level grants. JDBC URL passwords bypass key-based property
masking and appear in catalog responses and class-loader diagnostics.
Unsupported credential object types also return an internal error
instead of a client error.
Fixes #14638
### Does this PR introduce _any_ user-facing change?
Catalog credential users must receive the explicit secret privileges.
The returned credentials still carry the entire source account's
permissions. Migrate credential-bearing `jdbc-url` configurations to
credential properties/secret references before upgrading. PostgreSQL
loads the old configuration before ALTER, so an already-upgraded
deployment must use the previous server version to migrate first.
JDBC-backed Iceberg/Paimon `uri` properties are outside this URL
protection. URL masking is defensive protection for legacy properties
that reach the read path. No new privilege, dependency, or store
migration is introduced.
### How was this patch tested?
174 targeted tests passed with zero failures/errors/skips across the
fixes:
- 20 Docker integration tests across Spark 3.5 and 4.0 with MySQL,
simple authentication and OAuth/JWKS. These include rejecting Spark
catalog initialization when either secret privilege is missing,
successful initialization with both, and allowing metadata visibility
without credential access.
- 8 Java GVFS and 19 Python merge/credential-cache tests, including cold
filesystem creation after catalog denial and propagation of fileset
denial.
- 127 URL validation, JDBC configuration, property masking and REST
credential tests, including all combinations of the two required
privileges, unchanged fileset behavior, 23 data-source URL cases, and 8
Connector/J parser-backed encoded-userinfo and DNS SRV cases.
Updated the shared Spark authorization fixtures to grant both credential
privileges, fixing the failed Spark CI cases and the resulting dependent
table failures. Synchronized Java/Python API contracts, OpenAPI 403
responses, access-control and Glue/Paimon guidance; documented URL
migration timing and scope. Mutations disabling the catalog credential
guard or GVFS catalog-denial fallback fail their regressions; restored
code passes. Scoped Spotless, Black, Pylint, compilation, `:docs:build`
and `git diff --check` passed. Full Fork CI is running:
https://github.com/yuqi1129/gravitino/actions/runs/41954375290. Local
Spark tests used an embedded server with live MySQL; GVFS tests mock the
storage service. The updated cloud fileset authorization IT compiles but
was not run locally.
Authorization intentionally reuses the two established filter
expressions and their owner semantics. Their bounded duplicate
request-context lookup remains unchanged; combining authorization
context lifecycles is outside this fix.
---
.../apache/gravitino/authorization/Privilege.java | 8 ++-
.../apache/gravitino/authorization/Privileges.java | 12 ++--
.../gravitino/credential/SupportsCredentials.java | 9 +++
.../CloudStorageCredentialPropertyKeys.java | 10 +--
.../gravitino/catalog/jdbc/config/JdbcConfig.java | 8 ++-
.../catalog/jdbc/config/TestJdbcConfig.java | 13 ++++
.../jdbc/utils/TestDataSourceUrlValidation.java | 2 +-
.../catalog/mysql/TestMysqlJdbcUrlCredentials.java | 80 ++++++++++++++++++++++
.../gravitino/api/authorization/privileges.py | 20 ++++--
.../api/credential/supports_credentials.py | 9 +++
.../gravitino/filesystem/gvfs_base_operations.py | 8 ++-
.../tests/unittests/test_gvfs_merge_secrets.py | 53 +++++++++++++-
.../filesystem/hadoop/BaseGVFSOperations.java | 6 ++
.../hadoop/TestBaseGVFSOperationsSecrets.java | 47 ++++++++++++-
.../FilesetCatalogAuthorizationCredentialIT.java | 40 ++++++-----
.../org/apache/gravitino/utils/JdbcUrlUtils.java | 49 +++++++++++++
.../apache/gravitino/utils/TestJdbcUrlUtils.java | 52 ++++++++++++++
.../connector/HiddenPropertyMaskUtils.java | 4 +-
.../org/apache/gravitino/utils/ClassLoaderKey.java | 8 ++-
.../connector/TestHiddenPropertyMaskUtils.java | 29 ++++++++
docs/aws-glue-catalog.md | 2 +-
docs/lakehouse-paimon-catalog.md | 2 +-
docs/open-api/credentials.yaml | 12 ++++
docs/security/access-control.md | 9 +--
docs/security/credential-vending.md | 58 +++++++++-------
.../server/web/rest/ExceptionHandlers.java | 5 +-
.../rest/MetadataObjectCredentialOperations.java | 22 +++++-
.../TestMetadataObjectCredentialOperations.java | 80 ++++++++++++++++++++++
.../test/authorization/SparkAuthorizationIT.java | 42 ++++++++++--
.../authorization/SparkJwksAuthorizationIT.java | 8 ++-
30 files changed, 626 insertions(+), 81 deletions(-)
diff --git
a/api/src/main/java/org/apache/gravitino/authorization/Privilege.java
b/api/src/main/java/org/apache/gravitino/authorization/Privilege.java
index 083435cffa..b34132e1ed 100644
--- a/api/src/main/java/org/apache/gravitino/authorization/Privilege.java
+++ b/api/src/main/java/org/apache/gravitino/authorization/Privilege.java
@@ -162,14 +162,16 @@ public interface Privilege {
VIEW_SECRET_PROVIDERS(0L, 1L << 36),
/**
* The privilege required to call {@code getSecrets}. Without {@link
- * #INCLUDE_CREDENTIAL_SECRETS}, cloud access-key pairs are omitted from
the result. Does not
- * authorize {@code getCredentials}.
+ * #INCLUDE_CREDENTIAL_SECRETS}, cloud access-key pairs are omitted from
the result. Both
+ * privileges are also required for catalog {@code getCredentials}, unless
the caller owns the
+ * metalake.
*/
USE_SECRETS(0L, 1L << 37),
/**
* When held together with {@link #USE_SECRETS}, includes cloud access-key
pairs and other
* credential secrets in the {@code getSecrets} result. Alone it does not
authorize {@code
- * getSecrets}. Does not authorize {@code getCredentials}.
+ * getSecrets}. Both privileges are also required for catalog {@code
getCredentials}, unless the
+ * caller owns the metalake.
*/
INCLUDE_CREDENTIAL_SECRETS(0L, 1L << 38),
/** The privilege to create a semantic model. */
diff --git
a/api/src/main/java/org/apache/gravitino/authorization/Privileges.java
b/api/src/main/java/org/apache/gravitino/authorization/Privileges.java
index 95a15b6b7b..8307b25588 100644
--- a/api/src/main/java/org/apache/gravitino/authorization/Privileges.java
+++ b/api/src/main/java/org/apache/gravitino/authorization/Privileges.java
@@ -1445,10 +1445,11 @@ public class Privileges {
* The privilege required to call {@code getSecrets}. Without {@link
IncludeCredentialSecrets},
* cloud access-key pairs are omitted from the result.
*
- * <p>Intended for connectors that recover JDBC and similar secrets via
{@code getSecrets}, and
- * recover cloud access keys via {@code getCredentials} (which requires no
privilege). Callers
- * that are not the metalake owner and lack this privilege receive an empty
{@code getSecrets}
- * result rather than a forbidden error, once they can already access the
metadata object.
+ * <p>Catalog {@code getCredentials} requires both this privilege and {@link
+ * IncludeCredentialSecrets}, or metalake ownership, in addition to metadata
access. Fileset
+ * credential authorization is path-based. Callers that are not the metalake
owner and lack this
+ * privilege receive an empty {@code getSecrets} result rather than a
forbidden error, once they
+ * can already access the metadata object.
*/
public static final class UseSecrets extends GenericPrivilege<UseSecrets> {
@@ -1483,7 +1484,8 @@ public class Privileges {
/**
* When held together with {@link UseSecrets}, includes cloud access-key
pairs and other
- * credential secrets in the {@code getSecrets} result.
+ * credential secrets in the {@code getSecrets} result. Both privileges are
also required for
+ * catalog {@code getCredentials}, unless the caller is the metalake owner.
*
* <p>Does not authorize {@code getSecrets} or {@code getCredentials} by
itself. Metalake owners
* and holders of both privileges receive the full secrets map; holders of
only {@link UseSecrets}
diff --git
a/api/src/main/java/org/apache/gravitino/credential/SupportsCredentials.java
b/api/src/main/java/org/apache/gravitino/credential/SupportsCredentials.java
index f47649136d..8a25d92df2 100644
--- a/api/src/main/java/org/apache/gravitino/credential/SupportsCredentials.java
+++ b/api/src/main/java/org/apache/gravitino/credential/SupportsCredentials.java
@@ -24,6 +24,7 @@ import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.exceptions.NoSuchCredentialException;
/** Interface to get credentials. */
@@ -32,6 +33,11 @@ public interface SupportsCredentials {
/**
* Retrieves an array of {@link Credential} objects.
*
+ * <p>When authorization is enabled, catalog credentials require metadata
access plus both {@code
+ * USE_SECRETS} and {@code INCLUDE_CREDENTIAL_SECRETS}, or metalake
ownership. The credentials
+ * carry the source account's permissions; they are not scoped to individual
Gravitino tables.
+ * Fileset credentials use path-based authorization.
+ *
* @return An array of {@link Credential} objects. In most cases the array
only contains one
* credential. If the object like {@link
org.apache.gravitino.file.Fileset} contains multiple
* locations for different storages like HDFS, S3, the array will
contain multiple
@@ -40,6 +46,7 @@ public interface SupportsCredentials {
* credential provider only generate credential for the specific object
like {@link
* org.apache.gravitino.file.Fileset}, {@link
org.apache.gravitino.rel.Table}. There will be
* at most one credential for one credential type.
+ * @throws ForbiddenException If the caller lacks the required credential
privileges.
*/
Credential[] getCredentials();
@@ -50,6 +57,8 @@ public interface SupportsCredentials {
* the specific credentials.
* @return An {@link Credential} object with the specified credential type.
* @throws NoSuchCredentialException If the specific credential cannot be
found.
+ * @throws ForbiddenException If the caller lacks the privileges required by
{@link
+ * #getCredentials()}.
*/
default Credential getCredential(String credentialType) throws
NoSuchCredentialException {
Preconditions.checkArgument(
diff --git
a/catalogs/catalog-common/src/main/java/org/apache/gravitino/storage/CloudStorageCredentialPropertyKeys.java
b/catalogs/catalog-common/src/main/java/org/apache/gravitino/storage/CloudStorageCredentialPropertyKeys.java
index fd97207ed8..cc86b1be25 100644
---
a/catalogs/catalog-common/src/main/java/org/apache/gravitino/storage/CloudStorageCredentialPropertyKeys.java
+++
b/catalogs/catalog-common/src/main/java/org/apache/gravitino/storage/CloudStorageCredentialPropertyKeys.java
@@ -32,10 +32,12 @@ import
org.apache.gravitino.catalog.lakehouse.paimon.PaimonConstants;
* <p>GVFS must not consume these keys from REST catalog/schema/fileset {@code
properties()}
* responses (which may be masked as {@code ******}). Plaintext for hidden
static credentials,
* including {@code s3-access-key-id}, is recovered via {@code getSecrets()}
when the caller holds
- * {@code USE_SECRETS} and {@code INCLUDE_CREDENTIAL_SECRETS}, or via {@code
getCredentials()} (no
- * dedicated privilege). Masked placeholders are dropped by {@link
#omitStaticCredentialProperties}.
- * Callers with only {@code USE_SECRETS} receive {@code getSecrets()} with
cloud access-key pairs
- * omitted via {@link #omitCloudAccessKeyPairProperties}.
+ * {@code USE_SECRETS} and {@code INCLUDE_CREDENTIAL_SECRETS}, or via {@code
getCredentials()}.
+ * Catalog credential vending requires both privileges or metalake ownership,
in addition to
+ * metadata access; fileset credential vending uses path-based authorization.
Masked placeholders
+ * are dropped by {@link #omitStaticCredentialProperties}. Callers with only
{@code USE_SECRETS}
+ * receive {@code getSecrets()} with cloud access-key pairs omitted via {@link
+ * #omitCloudAccessKeyPairProperties}.
*
* <p>{@code azure-storage-account-name} is intentionally left non-hidden (and
not listed here):
* unlike S3/OSS/COS access key IDs, the account name is already disclosed in
ADLS URIs such as
diff --git
a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/config/JdbcConfig.java
b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/config/JdbcConfig.java
index c13d56aadc..5ef5348ab1 100644
---
a/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/config/JdbcConfig.java
+++
b/catalogs/catalog-jdbc-common/src/main/java/org/apache/gravitino/catalog/jdbc/config/JdbcConfig.java
@@ -26,6 +26,7 @@ import org.apache.gravitino.Config;
import org.apache.gravitino.config.ConfigBuilder;
import org.apache.gravitino.config.ConfigConstants;
import org.apache.gravitino.config.ConfigEntry;
+import org.apache.gravitino.utils.JdbcUrlUtils;
public class JdbcConfig extends Config {
@@ -161,7 +162,12 @@ public class JdbcConfig extends Config {
.createWithDefault(true);
public String getJdbcUrl() {
- return get(JDBC_URL);
+ String url = get(JDBC_URL);
+ if (JdbcUrlUtils.containsCredentials(url)) {
+ throw new IllegalArgumentException(
+ "Credentials in jdbc-url are not supported; use jdbc-user and
jdbc-password properties");
+ }
+ return url;
}
public String getJdbcDriver() {
diff --git
a/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/config/TestJdbcConfig.java
b/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/config/TestJdbcConfig.java
index cfb19f0029..8f78e941fd 100644
---
a/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/config/TestJdbcConfig.java
+++
b/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/config/TestJdbcConfig.java
@@ -20,11 +20,24 @@ package org.apache.gravitino.catalog.jdbc.config;
import com.google.common.collect.Maps;
import java.util.HashMap;
+import java.util.Map;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
public class TestJdbcConfig {
+ /** Checks URL credential rejection does not expose the supplied password. */
+ @Test
+ public void testUrlCredentialsAreRejectedWithoutEchoingTheSecret() {
+ String password = "never-echo-this";
+ JdbcConfig config =
+ new JdbcConfig(Map.of("jdbc-url",
"jdbc:postgresql://host/db?password=" + password));
+ IllegalArgumentException error =
+ Assertions.assertThrows(IllegalArgumentException.class,
config::getJdbcUrl);
+ Assertions.assertFalse(error.getMessage().contains(password));
+ Assertions.assertTrue(error.getMessage().contains("jdbc-password"));
+ }
+
@Test
public void testCreateDataSourceConfig() {
HashMap<String, String> properties = Maps.newHashMap();
diff --git
a/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/utils/TestDataSourceUrlValidation.java
b/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/utils/TestDataSourceUrlValidation.java
index c40f29cc35..07395251c7 100644
---
a/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/utils/TestDataSourceUrlValidation.java
+++
b/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/utils/TestDataSourceUrlValidation.java
@@ -184,7 +184,7 @@ public class TestDataSourceUrlValidation {
// instead of throwing), so the H2 guard still fires on the untouched
"jdbc:h2" prefix.
HashMap<String, String> properties = Maps.newHashMap();
properties.put(JdbcConfig.JDBC_DRIVER.getKey(), "org.postgresql.Driver");
- properties.put(JdbcConfig.JDBC_URL.getKey(),
"jdbc:h2:mem:test?password=100%");
+ properties.put(JdbcConfig.JDBC_URL.getKey(),
"jdbc:h2:mem:test?applicationName=100%");
properties.put(JdbcConfig.USERNAME.getKey(), "test");
properties.put(JdbcConfig.PASSWORD.getKey(), "test");
diff --git
a/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/TestMysqlJdbcUrlCredentials.java
b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/TestMysqlJdbcUrlCredentials.java
new file mode 100644
index 0000000000..979c1b5fef
--- /dev/null
+++
b/catalogs/catalog-jdbc-mysql/src/test/java/org/apache/gravitino/catalog/mysql/TestMysqlJdbcUrlCredentials.java
@@ -0,0 +1,80 @@
+/*
+ * 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.catalog.mysql;
+
+import com.mysql.cj.conf.ConnectionUrl;
+import com.mysql.cj.conf.ConnectionUrlParser;
+import com.mysql.cj.jdbc.NonRegisteringDriver;
+import java.sql.SQLException;
+import java.util.Map;
+import java.util.Properties;
+import org.apache.gravitino.catalog.jdbc.config.JdbcConfig;
+import org.apache.gravitino.utils.JdbcUrlUtils;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
+import org.junit.jupiter.params.provider.ValueSource;
+
+class TestMysqlJdbcUrlCredentials {
+ @ParameterizedTest
+ @ValueSource(
+ strings = {"jdbc:mysql+srv:", "jdbc:mysql+srv:loadbalance:",
"jdbc:mysql+srv:replication:"})
+ void testSrvPublicOptionsRemainUsableWithoutAllowingPasswords(String scheme)
throws SQLException {
+ String url =
+ scheme +
"//host/db?%70asswordCharacterEncoding=UTF-8&disconnectOnExpiredPasswords=false";
+ // Parse without resolving DNS SRV records or opening a connection.
+ Assertions.assertTrue(new NonRegisteringDriver().acceptsURL(url));
+ Map<String, String> properties =
ConnectionUrlParser.parseConnectionString(url).getProperties();
+ Assertions.assertEquals("UTF-8",
properties.get("passwordCharacterEncoding"));
+ Assertions.assertEquals("false",
properties.get("disconnectOnExpiredPasswords"));
+ Assertions.assertFalse(JdbcUrlUtils.containsCredentials(url));
+ Assertions.assertEquals(url, new JdbcConfig(Map.of("jdbc-url",
url)).getJdbcUrl());
+
+ String passwordUrl = url + "&password=hidden";
+ Assertions.assertEquals(
+ "hidden",
+
ConnectionUrlParser.parseConnectionString(passwordUrl).getProperties().get("password"));
+ Assertions.assertTrue(JdbcUrlUtils.containsCredentials(passwordUrl));
+ JdbcConfig config = new JdbcConfig(Map.of("jdbc-url", passwordUrl));
+ Assertions.assertThrows(IllegalArgumentException.class,
config::getJdbcUrl);
+ }
+
+ @ParameterizedTest
+ @CsvSource(
+ value = {
+ "jdbc:mysql://user:pass%2Fword@host/db|pass/word",
+ "jdbc:mysql://user:pass%3Fword@host/db|pass?word",
+ "jdbc:mysql://user:pass%23word@host/db|pass#word",
+ "jdbc:mysql://user:pass%252Fword@host/db|pass%2Fword",
+ "jdbc:mysql:loadbalance://user:pass%2Fword@host1,host2/db|pass/word"
+ },
+ delimiter = '|')
+ void testDriverRecognizesEncodedUserInfoThatGravitinoRejects(String url,
String password) {
+ // Parse with the pinned Connector/J without opening a network connection.
+ ConnectionUrl parsed = ConnectionUrl.getConnectionUrlInstance(url, new
Properties());
+ Assertions.assertEquals("user", parsed.getMainHost().getUser());
+ Assertions.assertEquals(password, parsed.getMainHost().getPassword());
+ Assertions.assertTrue(JdbcUrlUtils.containsCredentials(url));
+ JdbcConfig config = new JdbcConfig(Map.of("jdbc-url", url));
+ IllegalArgumentException error =
+ Assertions.assertThrows(IllegalArgumentException.class,
config::getJdbcUrl);
+ Assertions.assertFalse(error.getMessage().contains(password));
+ Assertions.assertFalse(error.getMessage().contains(url));
+ }
+}
diff --git a/clients/client-python/gravitino/api/authorization/privileges.py
b/clients/client-python/gravitino/api/authorization/privileges.py
index ed2fb80271..66990e343b 100644
--- a/clients/client-python/gravitino/api/authorization/privileges.py
+++ b/clients/client-python/gravitino/api/authorization/privileges.py
@@ -205,10 +205,16 @@ class Privilege(ABC):
"""The privilege to list configured secrets providers."""
USE_SECRETS = (0, 1 << 37)
- """Required to call getSecrets; cloud AK/SK omitted without
INCLUDE_CREDENTIAL_SECRETS."""
+ """Required to call getSecrets; cloud AK/SK need
INCLUDE_CREDENTIAL_SECRETS.
+
+ Catalog getCredentials also requires both privileges unless the caller
owns the metalake.
+ """
INCLUDE_CREDENTIAL_SECRETS = (0, 1 << 38)
- """With USE_SECRETS, include cloud credential secrets in the
getSecrets result."""
+ """With USE_SECRETS, include cloud credential secrets in getSecrets.
+
+ Catalog getCredentials also requires both privileges unless the caller
owns the metalake.
+ """
CREATE_SEMANTIC_MODEL = (0, 1 << 39)
"""The privilege to create a Semantic Model."""
@@ -1820,7 +1826,10 @@ class ViewSecretProviders(GenericPrivilege):
class UseSecrets(GenericPrivilege):
- """Required to call getSecrets; cloud AK/SK omitted without
INCLUDE_CREDENTIAL_SECRETS."""
+ """Required to call getSecrets; cloud AK/SK need
INCLUDE_CREDENTIAL_SECRETS.
+
+ Catalog getCredentials also requires both privileges unless the caller
owns the metalake.
+ """
_ALLOW_INSTANCE: Optional["UseSecrets"] = None
_DENY_INSTANCE: Optional["UseSecrets"] = None
@@ -1846,7 +1855,10 @@ class UseSecrets(GenericPrivilege):
class IncludeCredentialSecrets(GenericPrivilege):
- """With USE_SECRETS, include cloud credential secrets in the getSecrets
result."""
+ """With USE_SECRETS, include cloud credential secrets in getSecrets.
+
+ Catalog getCredentials also requires both privileges unless the caller
owns the metalake.
+ """
_ALLOW_INSTANCE: Optional["IncludeCredentialSecrets"] = None
_DENY_INSTANCE: Optional["IncludeCredentialSecrets"] = None
diff --git
a/clients/client-python/gravitino/api/credential/supports_credentials.py
b/clients/client-python/gravitino/api/credential/supports_credentials.py
index cf48566674..6dc1096da0 100644
--- a/clients/client-python/gravitino/api/credential/supports_credentials.py
+++ b/clients/client-python/gravitino/api/credential/supports_credentials.py
@@ -31,6 +31,12 @@ class SupportsCredentials(ABC):
def get_credentials(self) -> List[Credential]:
"""Retrieves a List of Credential objects.
+ With authorization enabled, catalog credentials require metadata access
+ plus both USE_SECRETS and INCLUDE_CREDENTIAL_SECRETS, or metalake
+ ownership. Catalog credentials carry the source account's permissions,
+ not individual Gravitino table grants. Fileset credentials use
path-based
+ authorization.
+
Returns:
A List of Credential objects. In most cases the array only contains
one credential. If the object like Fileset contains multiple locations
@@ -40,6 +46,8 @@ class SupportsCredentials(ABC):
for the catalog, like S3 token credential provider only generate
credential for the specific object like Fileset,Table. There will be at
most one credential for one credential type.
+ Raises:
+ ForbiddenException: If the caller lacks the required credential
privileges.
"""
pass
@@ -52,6 +60,7 @@ class SupportsCredentials(ABC):
Returns:
An Credential object with the specified credential type.
Raises:
+ ForbiddenException: If the caller lacks the privileges required by
get_credentials.
NoSuchCredentialException If the specific credential cannot be
found.
IllegalStateException if multiple credential can be found.
"""
diff --git a/clients/client-python/gravitino/filesystem/gvfs_base_operations.py
b/clients/client-python/gravitino/filesystem/gvfs_base_operations.py
index 56d8351bbf..86b02227aa 100644
--- a/clients/client-python/gravitino/filesystem/gvfs_base_operations.py
+++ b/clients/client-python/gravitino/filesystem/gvfs_base_operations.py
@@ -41,6 +41,7 @@ from gravitino.client.fileset_catalog import FilesetCatalog
from gravitino.client.gravitino_client_config import GravitinoClientConfig
from gravitino.exceptions.base import (
GravitinoRuntimeException,
+ ForbiddenException,
NoSuchCredentialException,
NoSuchLocationNameException,
NotFoundException,
@@ -562,7 +563,7 @@ class BaseGVFSOperations(ABC):
def _load_static_catalog_credential_info(catalog) -> Optional[Dict[str,
str]]:
"""Load expire==0 credential_info and map keys to GVFS option names.
- Returns an empty dict when credentials are unsupported or absent.
+ Returns an empty dict when catalog credentials are unsupported,
absent, or denied.
Returns None on transient REST failure.
"""
static_info: Dict[str, str] = {}
@@ -592,6 +593,11 @@ class BaseGVFSOperations(ABC):
"Catalog does not support credential recovery via
get_credentials: %s",
exc,
)
+ except ForbiddenException:
+ # Catalog-wide credentials are optional; fileset path
authorization is separate.
+ logger.debug(
+ "Catalog credentials are not permitted; using fileset
credential vending"
+ )
except RESTException as exc:
logger.warning(
"Failed to load static credentials via get_credentials;
continuing without them: %s",
diff --git a/clients/client-python/tests/unittests/test_gvfs_merge_secrets.py
b/clients/client-python/tests/unittests/test_gvfs_merge_secrets.py
index f26f3aaaf4..b2b2d90fa4 100644
--- a/clients/client-python/tests/unittests/test_gvfs_merge_secrets.py
+++ b/clients/client-python/tests/unittests/test_gvfs_merge_secrets.py
@@ -18,7 +18,11 @@ import unittest
from unittest.mock import MagicMock, patch
from urllib.error import URLError
-from gravitino.exceptions.base import NotFoundException, RESTException
+from gravitino.exceptions.base import (
+ ForbiddenException,
+ NotFoundException,
+ RESTException,
+)
from gravitino.filesystem.gvfs_default_operations import DefaultGVFSOperations
from gravitino.name_identifier import NameIdentifier
@@ -230,6 +234,7 @@ class TestGVFSMergeSecrets(unittest.TestCase):
def test_get_credentials_failures_do_not_abort_merge(self):
for exc in (
+ ForbiddenException("catalog credentials denied"),
NotFoundException("credentials endpoint missing"),
URLError("connection refused"),
):
@@ -251,6 +256,52 @@ class TestGVFSMergeSecrets(unittest.TestCase):
self.assertEqual(merged["s3-endpoint"],
"http://s3.example.com")
self.assertNotIn("s3-access-key-id", merged)
+ def test_catalog_denial_preserves_fileset_credential_authorization(self):
+ operations = DefaultGVFSOperations(
+ server_uri="http://localhost:8090", metalake_name="ml", options={}
+ )
+ catalog = MagicMock()
+ catalog.properties.return_value = {"s3-endpoint":
"http://s3.example.com"}
+ catalog.get_secrets.return_value = {}
+ catalog.support_credentials.return_value.get_credentials.side_effect =
(
+ ForbiddenException("catalog denied")
+ )
+ schema = catalog.as_schemas.return_value.load_schema.return_value
+ schema.properties.return_value = {}
+ schema.get_secrets.return_value = {}
+ fileset =
catalog.as_fileset_catalog.return_value.load_fileset.return_value
+ fileset.properties.return_value = {}
+ fileset.get_secrets.return_value = {}
+ fileset.storage_locations.return_value = {"default":
"s3://bucket/data"}
+ client = MagicMock()
+ client.load_catalog.return_value = catalog
+ scoped_credentials = [MagicMock()]
+ filesystem = MagicMock()
+ ident = NameIdentifier.of("ml", "catalog", "schema", "fs")
+ with (
+ patch.object(operations, "_get_gravitino_client",
return_value=client),
+ patch.object(operations, "_get_fileset", return_value=fileset),
+ patch.object(operations, "_get_user_defined_configs",
return_value={}),
+ patch.object(
+ operations,
+ "_get_credentials_with_cache",
+ return_value=scoped_credentials,
+ ) as vend,
+ patch.object(
+ operations, "_get_filesystem", return_value=filesystem
+ ) as create,
+ ):
+ self.assertIs(
+ filesystem,
+ operations._get_actual_filesystem_by_location_name(ident,
"default"),
+ )
+ vend.assert_called_once_with(ident, fileset, "default")
+ self.assertIs(create.call_args.args[0], scoped_credentials)
+ vend.side_effect = ForbiddenException("fileset denied")
+ with self.assertRaises(ForbiddenException):
+ operations._get_actual_filesystem_by_location_name(ident,
"default")
+ create.assert_called_once()
+
def test_skips_expiring_credentials(self):
operations = DefaultGVFSOperations(
server_uri="http://localhost:8090", metalake_name="ml", options={}
diff --git
a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.java
b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.java
index ae9c6c4ffd..833b4caeb5 100644
---
a/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.java
+++
b/clients/filesystem-hadoop3/src/main/java/org/apache/gravitino/filesystem/hadoop/BaseGVFSOperations.java
@@ -75,6 +75,7 @@ import org.apache.gravitino.client.GravitinoClient;
import org.apache.gravitino.credential.Credential;
import org.apache.gravitino.credential.SupportsCredentials;
import org.apache.gravitino.exceptions.CatalogNotInUseException;
+import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.exceptions.GravitinoRuntimeException;
import org.apache.gravitino.exceptions.NoSuchCatalogException;
import org.apache.gravitino.exceptions.NoSuchFilesetException;
@@ -1042,6 +1043,11 @@ public abstract class BaseGVFSOperations implements
Closeable {
"Catalog {} does not support credential recovery via getCredentials:
{}",
catalog.name(),
e.toString());
+ } catch (ForbiddenException e) {
+ // Catalog-wide credentials are optional; fileset path authorization is
separate.
+ LOG.debug(
+ "Catalog credentials for {} are not permitted; using fileset
credential vending",
+ catalog.name());
} catch (RESTException e) {
LOG.warn(
"Failed to load static credentials for catalog {} via
getCredentials; continuing without"
diff --git
a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.java
b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.java
index a612485d76..c559db3642 100644
---
a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.java
+++
b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/TestBaseGVFSOperationsSecrets.java
@@ -20,7 +20,14 @@ package org.apache.gravitino.filesystem.hadoop;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertSame;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
@@ -34,6 +41,7 @@ import org.apache.gravitino.credential.Credential;
import org.apache.gravitino.credential.S3SecretKeyCredential;
import org.apache.gravitino.credential.S3TokenCredential;
import org.apache.gravitino.credential.SupportsCredentials;
+import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.exceptions.RESTException;
import org.apache.gravitino.file.Fileset;
import org.apache.gravitino.file.FilesetCatalog;
@@ -44,6 +52,7 @@ import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.security.Credentials;
@@ -256,6 +265,40 @@ public class TestBaseGVFSOperationsSecrets {
assertEquals("http://s3.example.com", all.get("s3-endpoint"));
}
+ @Test
+ void testCatalogCredentialDenialDoesNotBlockFilesetCredentials() throws
Exception {
+ SupportsCredentials catalogCredentials = mock(SupportsCredentials.class);
+ when(catalogCredentials.getCredentials()).thenThrow(new
ForbiddenException("catalog denied"));
+ Catalog catalog =
+ mockCatalogWithCredentials(
+ Map.of("s3-endpoint", "http://s3.example.com"),
catalogCredentials);
+ Fileset fileset =
catalog.asFilesetCatalog().loadFileset(NameIdentifier.of("schema", "fs"));
+ when(fileset.storageLocations()).thenReturn(Map.of("default",
"s3a://bucket/data"));
+ SupportsCredentials scopedCredentials = mock(SupportsCredentials.class);
+ when(fileset.supportsCredentials()).thenReturn(scopedCredentials);
+ when(scopedCredentials.getCredentials())
+ .thenReturn(
+ new Credential[] {
+ new S3TokenCredential("SCOPED", "scoped-secret", "token",
Long.MAX_VALUE)
+ });
+ TestOps ops = spy(opsFor(catalog));
+ NameIdentifier ident = NameIdentifier.of("ml", "catalog", "schema", "fs");
+ doReturn(fileset).when(ops).getFileset(ident);
+ doReturn(true).when(ops).enableCredentialVending();
+ FileSystem filesystem = mock(FileSystem.class);
+ doReturn(filesystem).when(ops).getActualFileSystemByPath(any(Path.class),
anyMap());
+
+ assertSame(filesystem, ops.getActualFileSystemByLocationName(ident,
"default"));
+ verify(scopedCredentials).getCredentials();
+
+ ForbiddenException denied = new ForbiddenException("fileset denied");
+ when(scopedCredentials.getCredentials()).thenThrow(denied);
+ RuntimeException failure =
+ assertThrows(
+ RuntimeException.class, () ->
ops.getActualFileSystemByLocationName(ident, "default"));
+ assertSame(denied, failure.getCause());
+ }
+
@Test
public void testRestFailureDoesNotCacheEmptyStaticCredentials() throws
Exception {
SupportsCredentials credentials = mock(SupportsCredentials.class);
@@ -302,6 +345,8 @@ public class TestBaseGVFSOperationsSecrets {
private static TestOps opsFor(Catalog catalog) {
Configuration conf = new Configuration();
+ conf.setBoolean(
+
GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_AUTO_CREATE_LOCATION,
false);
conf.set(GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_CLIENT_METALAKE_KEY,
"ml");
conf.set(
GravitinoVirtualFileSystemConfiguration.FS_GRAVITINO_SERVER_URI_KEY,
@@ -335,7 +380,7 @@ public class TestBaseGVFSOperationsSecrets {
return catalog;
}
- private static final class TestOps extends BaseGVFSOperations {
+ private static class TestOps extends BaseGVFSOperations {
private final GravitinoClient client;
private TestOps(Configuration configuration, GravitinoClient client) {
diff --git
a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/integration/test/FilesetCatalogAuthorizationCredentialIT.java
b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/integration/test/FilesetCatalogAuthorizationCredentialIT.java
index 4673c02d6f..52068c0efd 100644
---
a/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/integration/test/FilesetCatalogAuthorizationCredentialIT.java
+++
b/clients/filesystem-hadoop3/src/test/java/org/apache/gravitino/filesystem/hadoop/integration/test/FilesetCatalogAuthorizationCredentialIT.java
@@ -195,24 +195,28 @@ public class FilesetCatalogAuthorizationCredentialIT
extends BaseIT {
void testGetCatalogCredentialWithPrivilege() {
GravitinoMetalake normalUserMetalake =
normalUserClient.loadMetalake(metalakeName);
Catalog catalog = normalUserMetalake.loadCatalog(catalogName);
- catalog.supportsCredentials().getCredentials();
-
- metalake.revokePrivilegesFromRole(
- ROLE_NAME,
- MetadataObjects.of(null, catalogName, MetadataObject.Type.CATALOG),
- ImmutableSet.of(Privileges.UseCatalog.allow()));
-
- // Normal user without specific catalog privileges cannot get catalog
credentials
- assertThrows(
- ForbiddenException.class,
- () -> {
- catalog.supportsCredentials().getCredentials();
- });
-
- metalake.grantPrivilegesToRole(
- ROLE_NAME,
- MetadataObjects.of(null, catalogName, MetadataObject.Type.CATALOG),
- ImmutableSet.of(Privileges.UseCatalog.allow()));
+ MetadataObject object = MetadataObjects.of(null, catalogName,
MetadataObject.Type.CATALOG);
+ assertThrows(ForbiddenException.class, () ->
catalog.supportsCredentials().getCredentials());
+ try {
+ metalake.grantPrivilegesToRole(
+ ROLE_NAME, object, ImmutableSet.of(Privileges.UseSecrets.allow()));
+ assertThrows(ForbiddenException.class, () ->
catalog.supportsCredentials().getCredentials());
+ metalake.grantPrivilegesToRole(
+ ROLE_NAME, object,
ImmutableSet.of(Privileges.IncludeCredentialSecrets.allow()));
+
Assertions.assertTrue(catalog.supportsCredentials().getCredentials().length >
0);
+
+ metalake.revokePrivilegesFromRole(
+ ROLE_NAME, object, ImmutableSet.of(Privileges.UseCatalog.allow()));
+ assertThrows(ForbiddenException.class, () ->
catalog.supportsCredentials().getCredentials());
+ } finally {
+ metalake.grantPrivilegesToRole(
+ ROLE_NAME, object, ImmutableSet.of(Privileges.UseCatalog.allow()));
+ metalake.revokePrivilegesFromRole(
+ ROLE_NAME,
+ object,
+ ImmutableSet.of(
+ Privileges.UseSecrets.allow(),
Privileges.IncludeCredentialSecrets.allow()));
+ }
}
@Test
diff --git a/common/src/main/java/org/apache/gravitino/utils/JdbcUrlUtils.java
b/common/src/main/java/org/apache/gravitino/utils/JdbcUrlUtils.java
index fcc2b1046f..e4205a2d34 100644
--- a/common/src/main/java/org/apache/gravitino/utils/JdbcUrlUtils.java
+++ b/common/src/main/java/org/apache/gravitino/utils/JdbcUrlUtils.java
@@ -32,6 +32,9 @@ import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.exceptions.GravitinoRuntimeException;
@@ -43,6 +46,15 @@ import
org.apache.gravitino.exceptions.GravitinoRuntimeException;
*/
public class JdbcUrlUtils {
+ private static final Pattern URL_PARAMETER =
Pattern.compile("(?:[?;&,(]|^)([^=?;&,()]+)=");
+ private static final List<String> CREDENTIAL_PARAMETER_KEYWORDS =
+ Arrays.asList("password", "passwd", "pwd", "secret", "token",
"credential");
+ // Connector/J options whose names contain "password" but whose values are
not credentials.
+ private static final List<String> NON_SECRET_MYSQL_PARAMETERS =
+ Arrays.asList("passwordcharacterencoding",
"disconnectonexpiredpasswords");
+ private static final Pattern USER_INFO =
+
Pattern.compile("(?i)(?://[^/?#]*@|jdbc:oracle:(?:thin|oci|oci8):[^/@]+/[^@]*@)");
+
// The DBCP2 connection-pool property whose value is a list of connection
properties forwarded
// verbatim to the JDBC driver. Unsafe parameters smuggled here would
otherwise evade a check
// that only inspects the URL string and the raw config values.
@@ -75,6 +87,26 @@ public class JdbcUrlUtils {
// Utility class, no instantiation allowed
}
+ /**
+ * Detects credentials embedded in JDBC URLs, including encoded parameter
names.
+ *
+ * @param url the JDBC URL, or null
+ * @return whether the URL must not be exposed as a public catalog property
+ */
+ public static boolean containsCredentials(@Nullable String url) {
+ if (url == null) {
+ return false;
+ }
+ // Determine the driver family before URLDecoder turns the DNS SRV
scheme's '+' into a space.
+ String lowerUrl = url.toLowerCase(Locale.ROOT);
+ boolean mysqlUrl = lowerUrl.startsWith("jdbc:mysql:") ||
lowerUrl.startsWith("jdbc:mysql+srv:");
+ // Decoding a password can introduce '/', '?' or '#' and change the
authority boundaries.
+ // Inspect raw user information before scanning decoded parameter names.
+ return USER_INFO.matcher(url).find()
+ || decodedFormsForScan(url).stream()
+ .anyMatch(form -> containsCredentialParameters(form, mysqlUrl));
+ }
+
/**
* Validates the JDBC configuration by checking the driver and URL for
unsafe parameters.
*
@@ -153,6 +185,23 @@ public class JdbcUrlUtils {
}
}
+ private static boolean containsCredentialParameters(String url, boolean
mysqlUrl) {
+ if (USER_INFO.matcher(url).find()) {
+ return true;
+ }
+ Matcher parameters = URL_PARAMETER.matcher(url);
+ while (parameters.find()) {
+ String key = parameters.group(1);
+ if (mysqlUrl && NON_SECRET_MYSQL_PARAMETERS.contains(key)) {
+ continue;
+ }
+ if (CREDENTIAL_PARAMETER_KEYWORDS.stream().anyMatch(key::contains)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
private static String recursiveDecode(String url) {
String prev;
String decoded = url;
diff --git
a/common/src/test/java/org/apache/gravitino/utils/TestJdbcUrlUtils.java
b/common/src/test/java/org/apache/gravitino/utils/TestJdbcUrlUtils.java
index 93557de8c6..a7a23a2c38 100644
--- a/common/src/test/java/org/apache/gravitino/utils/TestJdbcUrlUtils.java
+++ b/common/src/test/java/org/apache/gravitino/utils/TestJdbcUrlUtils.java
@@ -28,8 +28,60 @@ import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.parallel.ResourceAccessMode;
import org.junit.jupiter.api.parallel.ResourceLock;
import org.junit.jupiter.api.parallel.Resources;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
public class TestJdbcUrlUtils {
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "jdbc:postgresql://host/db?user=u&password=hidden",
+ "jdbc:postgresql://host/db?%70assword=hidden",
+ "jdbc:sqlserver://host;databaseName=db;PASSWORD={hidden;value}",
+ "jdbc:mysql://user:hidden@host/db",
+ "jdbc:mysql://user:pass%2Fword@host/db",
+ "jdbc:mysql://user:pass%3Fword@host/db",
+ "jdbc:mysql://user:pass%23word@host/db",
+ "jdbc:mysql://user:pass%252Fword@host/db",
+ "jdbc:mysql:loadbalance://user:pass%2Fword@host1,host2/db",
+ "jdbc:mysql://(host=host,user=u,password=hidden)/db",
+ "jdbc:oracle:oci:user/hidden@service",
+ "jdbc:oracle:thin:user/hidden@host:1521/db",
+ "jdbc:postgresql://host/db?sslpassword=hidden",
+ "jdbc:sqlserver://host;accessToken=hidden",
+ "jdbc:postgresql://host/db?password=",
+ "jdbc:postgresql://host/db?%2570assword=hidden#%zz",
+ "jdbc:mysql://host/db?passwordCharacterEncoding=UTF-8&password=hidden",
+
"jdbc:mysql://host/db?disconnectOnExpiredPasswords=false&%70assword2=hidden",
+ "jdbc:mysql://host/db?password1=hidden",
+ "jdbc:mysql://host/db?password3=hidden",
+
"jdbc:mysql+srv://host/db?passwordCharacterEncoding=UTF-8&password=hidden",
+
"jdbc:mysql+srv:loadbalance://host/db?disconnectOnExpiredPasswords=false&%70assword2=hidden",
+ "jdbc:postgresql://host/db?passwordCharacterEncoding=hidden"
+ })
+ void testCredentialsAreDetected(String url) {
+ Assertions.assertTrue(JdbcUrlUtils.containsCredentials(url));
+ }
+
+ @ParameterizedTest
+ @ValueSource(
+ strings = {
+ "jdbc:postgresql://host/password?user=reader&sslmode=require",
+ "jdbc:sqlserver://host;databaseName=db;encrypt=true",
+ "jdbc:oracle:thin:@host:1521/service",
+ "jdbc:sqlite::memory:",
+ "jdbc:mysql://host/db?useSSL=true",
+ "jdbc:mysql://host/db?passwordCharacterEncoding=UTF-8",
+ "jdbc:mysql://host/db?disconnectOnExpiredPasswords=false",
+
"jdbc:mysql://host/db?%70asswordCharacterEncoding=UTF-8&disconnectOnExpiredPasswords=false",
+ "jdbc:mysql+srv://host/db?passwordCharacterEncoding=UTF-8",
+
"jdbc:mysql+srv:loadbalance://host/db?disconnectOnExpiredPasswords=false",
+
"jdbc:mysql+srv:replication://host/db?%70asswordCharacterEncoding=UTF-8&disconnectOnExpiredPasswords=false"
+ })
+ void testPublicConnectionOptionsRemainVisible(String url) {
+ Assertions.assertFalse(JdbcUrlUtils.containsCredentials(url));
+ Assertions.assertFalse(JdbcUrlUtils.containsCredentials(null));
+ }
@Test
public void whenMalformedUrlGiven_ShouldFallBackToLastDecodedForm() {
diff --git
a/core/src/main/java/org/apache/gravitino/connector/HiddenPropertyMaskUtils.java
b/core/src/main/java/org/apache/gravitino/connector/HiddenPropertyMaskUtils.java
index e4f407fc56..c14487402d 100644
---
a/core/src/main/java/org/apache/gravitino/connector/HiddenPropertyMaskUtils.java
+++
b/core/src/main/java/org/apache/gravitino/connector/HiddenPropertyMaskUtils.java
@@ -35,6 +35,7 @@ import javax.annotation.Nullable;
import org.apache.commons.lang3.StringUtils;
import org.apache.gravitino.json.JsonUtils;
import org.apache.gravitino.secret.SecretPropertyUtils;
+import org.apache.gravitino.utils.JdbcUrlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -129,7 +130,8 @@ public final class HiddenPropertyMaskUtils {
boolean reserved = metadata.isReservedProperty(key);
if (hidden && reserved) {
keysToOmit.add(key);
- } else if (hidden
+ } else if (("jdbc-url".equalsIgnoreCase(key) &&
JdbcUrlUtils.containsCredentials(value))
+ || hidden
|| SecretPropertyUtils.isSecretProperty(key, value)
|| (!metadata.containsProperty(key) &&
SecretPropertyUtils.isSensitivePropertyKey(key))) {
keysToMask.add(key);
diff --git a/core/src/main/java/org/apache/gravitino/utils/ClassLoaderKey.java
b/core/src/main/java/org/apache/gravitino/utils/ClassLoaderKey.java
index fbc5677c8e..d73a344d52 100644
--- a/core/src/main/java/org/apache/gravitino/utils/ClassLoaderKey.java
+++ b/core/src/main/java/org/apache/gravitino/utils/ClassLoaderKey.java
@@ -65,6 +65,12 @@ public class ClassLoaderKey {
@Override
public String toString() {
- return "ClassLoaderKey{" + "provider='" + provider + '\'' + ",
properties=" + properties + '}';
+ return "ClassLoaderKey{"
+ + "provider='"
+ + provider
+ + '\''
+ + ", propertyNames="
+ + properties.keySet()
+ + '}';
}
}
diff --git
a/core/src/test/java/org/apache/gravitino/connector/TestHiddenPropertyMaskUtils.java
b/core/src/test/java/org/apache/gravitino/connector/TestHiddenPropertyMaskUtils.java
index c646e47fc1..8fb062cf97 100644
---
a/core/src/test/java/org/apache/gravitino/connector/TestHiddenPropertyMaskUtils.java
+++
b/core/src/test/java/org/apache/gravitino/connector/TestHiddenPropertyMaskUtils.java
@@ -28,9 +28,11 @@ import org.apache.gravitino.Config;
import org.apache.gravitino.Configs;
import org.apache.gravitino.json.JsonUtils;
import org.apache.gravitino.secret.SecretPropertyUtils;
+import org.apache.gravitino.utils.ClassLoaderKey;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.mockito.Mockito;
public class TestHiddenPropertyMaskUtils {
@@ -39,6 +41,33 @@ public class TestHiddenPropertyMaskUtils {
SecretPropertyUtils.configureSensitiveKeyKeywords(new Config(false) {});
}
+ @Test
+ void testLegacyJdbcUrlIsMaskedEvenWhenDeclaredPublic() {
+ PropertiesMetadata metadata = Mockito.mock(PropertiesMetadata.class);
+ Mockito.when(metadata.containsProperty("jdbc-url")).thenReturn(true);
+ for (String url :
+ new String[] {
+ "jdbc:postgresql://host/db?password=hidden",
+ "jdbc:mysql://user:pass%2Fword@host/db",
+ "jdbc:mysql://user:pass%3Fword@host/db",
+ "jdbc:mysql://user:pass%23word@host/db",
+ "jdbc:mysql:loadbalance://user:pass%252Fword@host1,host2/db"
+ }) {
+ MaskAndOmitKeys keys =
+ HiddenPropertyMaskUtils.classifyHiddenProperties(Map.of("jdbc-url",
url), metadata);
+ Assertions.assertTrue(keys.keysToMask().contains("jdbc-url"), url);
+ }
+
+ ClassLoaderKey key =
+ new ClassLoaderKey(
+ "jdbc-postgresql", Map.of("jdbc-url",
"jdbc:postgresql://host/db?password=hidden"));
+ Assertions.assertFalse(key.toString().contains("password=hidden"));
+ Assertions.assertEquals(
+ key,
+ new ClassLoaderKey(
+ "jdbc-postgresql", Map.of("jdbc-url",
"jdbc:postgresql://host/db?password=hidden")));
+ }
+
@Test
void testMaskHiddenPropertiesByName() {
Map<String, String> properties =
diff --git a/docs/aws-glue-catalog.md b/docs/aws-glue-catalog.md
index 8f13dce87b..49cd8ce2d1 100644
--- a/docs/aws-glue-catalog.md
+++ b/docs/aws-glue-catalog.md
@@ -64,7 +64,7 @@ Refer to [Manage Catalogs and
Schemas](./manage-catalogs-and-schemas.md#catalog-
:::note
Sensitive catalog properties such as `aws-access-key-id` /
`aws-secret-access-key` are hidden from the default load catalog response.
Recover them via:
-- `getCredentials` / `AwsSecretKeyCredential` (and remapped
`S3SecretKeyCredential` when auto-detected) — no dedicated privilege beyond
loading the catalog
+- `getCredentials` / `AwsSecretKeyCredential` (and remapped
`S3SecretKeyCredential` when auto-detected) — requires catalog access plus both
`USE_SECRETS` and `INCLUDE_CREDENTIAL_SECRETS`, or metalake ownership
- `getSecrets` / `GET .../objects/{type}/{fullName}/secrets` with
`USE_SECRETS` and `INCLUDE_CREDENTIAL_SECRETS`
See [credential vending](security/credential-vending.md) for details.
diff --git a/docs/lakehouse-paimon-catalog.md b/docs/lakehouse-paimon-catalog.md
index 2cc78c4f07..fd7fee8cac 100644
--- a/docs/lakehouse-paimon-catalog.md
+++ b/docs/lakehouse-paimon-catalog.md
@@ -138,7 +138,7 @@ Refer to [Manage Catalogs and
Schemas](./manage-catalogs-and-schemas.md#catalog-
:::note
Sensitive catalog properties such as `jdbc-password` and DLF credential keys
are hidden from the default load catalog response (`jdbc-user` is returned in
plaintext). Recover JDBC / DLF credential fields via either path:
-- `getCredentials` / `JdbcCredential` / `DlfSecretKeyCredential` (no dedicated
privilege beyond loading the catalog)
+- `getCredentials` / `JdbcCredential` / `DlfSecretKeyCredential` (requires
catalog access plus both `USE_SECRETS` and `INCLUDE_CREDENTIAL_SECRETS`, or
metalake ownership)
- `getSecrets` / `GET .../objects/{type}/{fullName}/secrets` with
`USE_SECRETS` (DLF cloud access-key pairs also need
`INCLUDE_CREDENTIAL_SECRETS`)
Other non-credential secrets (secret-manager URNs, declared `hidden`
properties, undeclared sensitive-named keys) use `getSecrets` only.
diff --git a/docs/open-api/credentials.yaml b/docs/open-api/credentials.yaml
index 4f5106c396..cf18e4e491 100644
--- a/docs/open-api/credentials.yaml
+++ b/docs/open-api/credentials.yaml
@@ -29,6 +29,12 @@ paths:
- credentials
summary: Get credentials
operationId: getCredentials
+ description: >
+ Retrieves credentials for a catalog or fileset. When authorization is
enabled,
+ catalog credentials require metadata access plus both USE_SECRETS and
+ INCLUDE_CREDENTIAL_SECRETS, or metalake ownership. Catalog credentials
carry
+ the source account's permissions and are not scoped to individual
Gravitino
+ tables. Fileset credentials use path-based authorization.
responses:
"200":
description: Returns the list of credential objects associated with
specified metadata object.
@@ -41,6 +47,12 @@ paths:
$ref: "#/components/examples/CredentialResponse"
"400":
$ref: "./openapi.yaml#/components/responses/BadRequestErrorResponse"
+ "403":
+ description: Forbidden - The caller lacks the required credential
privileges.
+ content:
+ application/vnd.gravitino.v1+json:
+ schema:
+ $ref: "./openapi.yaml#/components/schemas/ErrorModel"
"404":
description: Not Found - The specified metalake does not exist
content:
diff --git a/docs/security/access-control.md b/docs/security/access-control.md
index a406385fde..d1f1725539 100755
--- a/docs/security/access-control.md
+++ b/docs/security/access-control.md
@@ -203,8 +203,8 @@ sets the scope of the grant. Binding a privilege to a type
not listed for it is
| `REGISTER_MODEL` | Metalake, Catalog, Schema
| Register models in any schema in scope
|
| `LINK_MODEL_VERSION` | Metalake, Catalog, Schema, Model
| Link versions to any model in scope
|
| `USE_MODEL` | Metalake, Catalog, Schema, Model
| Read the metadata of, and download versions of, any
model in scope |
-| `USE_SECRETS` | Metalake, Catalog, Schema, Table, View,
Topic, Fileset, Model | Call `getSecrets` (cloud access-key pairs omitted
unless also granted `INCLUDE_CREDENTIAL_SECRETS`) |
-| `INCLUDE_CREDENTIAL_SECRETS` | Metalake, Catalog, Schema, Table, View,
Topic, Fileset, Model | With `USE_SECRETS`, include cloud access-key pairs in
the `getSecrets` result |
+| `USE_SECRETS` | Metalake, Catalog, Schema, Table, View,
Topic, Fileset, Model | Call `getSecrets` (cloud access-key pairs omitted
unless also granted `INCLUDE_CREDENTIAL_SECRETS`); required with
`INCLUDE_CREDENTIAL_SECRETS` for catalog `getCredentials` |
+| `INCLUDE_CREDENTIAL_SECRETS` | Metalake, Catalog, Schema, Table, View,
Topic, Fileset, Model | With `USE_SECRETS`, include cloud access-key pairs in
`getSecrets` and authorize catalog `getCredentials` |
| `REGISTER_FUNCTION` | Metalake, Catalog, Schema
| Register functions in any schema in scope
|
| `EXECUTE_FUNCTION` | Metalake, Catalog, Schema, Function
| Read the metadata of, and execute, any function in
scope |
| `MODIFY_FUNCTION` | Metalake, Catalog, Schema, Function
| Alter or drop any function in scope
|
@@ -292,8 +292,9 @@ Table statistics follow the table itself: reading them
takes `SELECT_TABLE` or `
writing them takes `MODIFY_TABLE`. Model versions follow the model:
`USE_MODEL` to read, owner to
alter or delete. Fetching plaintext secrets (`getSecrets`) requires owning the
metalake or holding
`USE_SECRETS`. Cloud access-key pairs are included only when the caller is the
metalake owner or also
-holds `INCLUDE_CREDENTIAL_SECRETS`. Vend credentials (`getCredentials`)
requires no dedicated
-privilege beyond being able to load the object. Callers who can load the
object but lack
+holds `INCLUDE_CREDENTIAL_SECRETS`. Catalog credential vending
(`getCredentials`) requires metadata access plus both
+`USE_SECRETS` and `INCLUDE_CREDENTIAL_SECRETS`, or metalake ownership. Missing
either privilege
+returns a forbidden error. Fileset credential vending retains its path-based
authorization. Callers who can load the object but lack
`USE_SECRETS` receive an empty `getSecrets` result rather than a forbidden
error.
The View row applies to metadata operations through both the native Gravitino
REST API and the
diff --git a/docs/security/credential-vending.md
b/docs/security/credential-vending.md
index bf3b0b183c..dca36c9f8c 100755
--- a/docs/security/credential-vending.md
+++ b/docs/security/credential-vending.md
@@ -143,31 +143,18 @@ The inferred provider list is returned as the catalog's
`credential-providers` p
Four providers have no inference rule and must always be set explicitly:
`s3-token`, `oss-token`, `adls-token`, and `aws-irsa`. In particular, setting
`s3-role-arn` without `credential-providers` does not enable `s3-token`. The
catalog falls back to `s3-secret-key` and vends the static access key instead,
which is long-lived and not scoped to the table path. Set
`credential-providers` explicitly whenever you want token-based vending.
-### Static providers and `getCredentials` privilege risk
+### Static providers and `getCredentials` privileges
-Static providers such as `s3-secret-key`, `oss-secret-key`, `cos-secret-key`,
`azure-account-key`,
-`jdbc-user-password`, `aws-secret-key`, and `dlf-secret-key` return the
configured long-lived
-plaintext keys from `getCredentials` / `GET .../credentials`. That endpoint
does **not** require a
-dedicated privilege beyond being able to load the metadata object (unlike
`getSecrets`, which
-requires `USE_SECRETS`, with cloud access-key pairs gated by
`INCLUDE_CREDENTIAL_SECRETS`).
+Static providers return the configured source account's long-lived
credentials. Catalog-level
+`getCredentials` requires metadata access plus both `USE_SECRETS` and
+`INCLUDE_CREDENTIAL_SECRETS`, or metalake ownership. Grant these privileges
only to trusted
+connectors/operators: the credentials carry all source-account permissions and
do not enforce
+Gravitino table-level grants or denies when used directly against the source.
-**Risk:** any principal that can load a catalog (or fileset) configured with
these static providers
-can retrieve the same static AK/SK or JDBC password that Gravitino uses
server-side.
-
-**Temporary mitigation** until provider-level authorization is tightened:
-
-- Prefer short-lived token providers (`s3-token`, `oss-token`, `adls-token`,
`gcs-token`,
- `cos-token`, `aws-irsa`) over static `*-secret-key` / `azure-account-key` /
`jdbc-user-password`
- whenever possible. These providers are only accepted on
- Fileset and Iceberg catalogs.
-- When static providers are unavoidable, grant load / use privileges only to
trusted principals
- (connectors and operators that must recover credentials).
-- Do not treat `getCredentials` as a secrets-protected API for static keys;
use `USE_SECRETS` /
- `INCLUDE_CREDENTIAL_SECRETS` and `getSecrets` when you need privilege-gated
plaintext access.
-
-A follow-up should track a lasting fix (for example privilege checks specific
to static
-credentials, or refusing to vend static secret-key credentials through
`getCredentials` when
-authorization is enabled).
+Fileset credential authorization remains path-based. Static fileset
credentials may still
+have broader source access than the requested path, so prefer short-lived
scoped providers
+(`s3-token`, `oss-token`, `adls-token`, `gcs-token`, `cos-token`, `aws-irsa`)
when available.
+Do not grant fileset access backed by unrestricted static accounts to
untrusted principals.
## S3
@@ -515,7 +502,7 @@ Bundle jars on Maven Central:
## Upgrading From a Release Earlier Than 1.3.0
-Sensitive catalog properties such as `s3-access-key-id`,
`s3-secret-access-key`, `jdbc-password`, `aws-access-key-id` /
`aws-secret-access-key` (Glue), and `dlf-access-key-id` /
`dlf-access-key-secret` / `dlf-security-token` (Paimon DLF) are masked or
excluded from the default `GET /api/metalakes/{metalake}/catalogs/{catalog}`
response (`jdbc-user` and `azure-storage-account-name` are returned in
plaintext when not hidden). Plaintext secrets are available via `getSecrets`
when the caller [...]
+Sensitive catalog properties such as `s3-access-key-id`,
`s3-secret-access-key`, `jdbc-password`, `aws-access-key-id` /
`aws-secret-access-key` (Glue), and `dlf-access-key-id` /
`dlf-access-key-secret` / `dlf-security-token` (Paimon DLF) are masked or
excluded from the default `GET /api/metalakes/{metalake}/catalogs/{catalog}`
response (`jdbc-user` and `azure-storage-account-name` are returned in
plaintext when not hidden). Plaintext secrets are available via `getSecrets`
when the caller [...]
For a zero-downtime migration, set the following in `gravitino.conf`:
@@ -525,3 +512,26 @@ gravitino.catalog.credential.backfillToProperties = true
```
The Gravitino server then re-includes the hidden properties in its catalog GET
responses. Turn it off once all clients use the Gravitino credential endpoint,
since it exposes credentials in plaintext.
+
+### Catalog credential access
+
+With authorization enabled, catalog-level credential vending requires both
`USE_SECRETS`
+and `INCLUDE_CREDENTIAL_SECRETS`, or metalake ownership, in addition to
metadata access.
+`USE_CATALOG` alone does not allow retrieving the source account. Engine users
that need
+catalog credentials must receive these privileges explicitly. Catalog
credentials are
+unscoped: they carry the source account's privileges, including access beyond
a single
+Gravitino table. Fileset path-based credential authorization is unchanged.
GVFS skips an optional catalog
+credential lookup when it is forbidden, then uses the fileset credential
endpoint; denial at
+that fileset endpoint still prevents access.
+
+For relational JDBC catalogs, `jdbc-url` must not contain passwords, tokens,
or inline user
+information. Move login credentials to `jdbc-user` and `jdbc-password` (or
secret references)
+**before upgrading**. Legacy credential-bearing `jdbc-url` properties are
masked when they
+reach the property read path, but loading a catalog can fail earlier during
configuration
+validation. PostgreSQL catalog ALTER also loads the old configuration first,
so it cannot
+repair such a URL after upgrading. If already upgraded, use the previous
server version to
+migrate the catalog configuration before upgrading again.
+
+This URL validation and masking apply to relational JDBC catalogs' `jdbc-url`
property;
+JDBC-backed Iceberg/Paimon `uri` properties are outside this change.
Class-loader diagnostics
+show property names only.
diff --git
a/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
b/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
index 2c8dcdcceb..07032081a7 100644
---
a/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
+++
b/server/src/main/java/org/apache/gravitino/server/web/rest/ExceptionHandlers.java
@@ -790,12 +790,15 @@ public class ExceptionHandlers {
@Override
public Response handle(OperationType op, String credential, String parent,
Exception e) {
- String errorMsg = getCredentialErrorMsg(parent, getErrorMsg(e));
+ String errorMsg = getCredentialErrorMsg(credential, getErrorMsg(e));
LOG.warn(errorMsg, e);
if (e instanceof IllegalArgumentException) {
return Utils.illegalArguments(errorMsg, e);
+ } else if (e instanceof ForbiddenException) {
+ return Utils.forbidden(errorMsg, e);
+
} else if (e instanceof NotFoundException) {
return Utils.notFound(errorMsg, e);
diff --git
a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectCredentialOperations.java
b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectCredentialOperations.java
index 196e1619a0..9af4f0c639 100644
---
a/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectCredentialOperations.java
+++
b/server/src/main/java/org/apache/gravitino/server/web/rest/MetadataObjectCredentialOperations.java
@@ -29,7 +29,6 @@ import java.util.Set;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
-import javax.ws.rs.NotSupportedException;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
@@ -46,6 +45,7 @@ import org.apache.gravitino.credential.CredentialPrivilege;
import org.apache.gravitino.dto.credential.CredentialDTO;
import org.apache.gravitino.dto.responses.CredentialResponse;
import org.apache.gravitino.dto.util.DTOConverters;
+import org.apache.gravitino.exceptions.ForbiddenException;
import org.apache.gravitino.metrics.MetricNames;
import org.apache.gravitino.server.authorization.MetadataAuthzHelper;
import
org.apache.gravitino.server.authorization.annotations.AuthorizationExpression;
@@ -102,12 +102,28 @@ public class MetadataObjectCredentialOperations {
MetadataObjects.parse(
fullName,
MetadataObject.Type.valueOf(type.toUpperCase(Locale.ROOT)));
if (!supportsCredentialOperations(object)) {
- throw new NotSupportedException(
- "Doesn't support credential operations for metadata object
type");
+ throw new IllegalArgumentException(
+ "Credential operations are not supported for metadata object
type "
+ + object.type());
}
NameIdentifier identifier =
MetadataObjectUtil.toEntityIdent(metalake, object);
Entity.EntityType entityType =
MetadataObjectUtil.toEntityType(object);
+ // Catalog credentials are not restricted to individual tables or
paths. Metadata access
+ // alone must not grant the catalog account's source privileges.
+ if (object.type() == MetadataObject.Type.CATALOG
+ && (!MetadataAuthzHelper.checkAccess(
+ identifier,
+ entityType,
+
AuthorizationExpressionConstants.FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION)
+ || !MetadataAuthzHelper.checkAccess(
+ identifier,
+ entityType,
+ AuthorizationExpressionConstants
+
.FILTER_INCLUDE_CREDENTIAL_SECRETS_AUTHORIZATION_EXPRESSION))) {
+ throw new ForbiddenException(
+ "Catalog credentials require USE_SECRETS and
INCLUDE_CREDENTIAL_SECRETS");
+ }
Map<String, String> filteredFilesetHeaders =
Utils.filterFilesetCredentialHeaders(httpRequest);
diff --git
a/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectCredentialOperations.java
b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectCredentialOperations.java
index 8e9d06c95d..ede3595f4d 100644
---
a/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectCredentialOperations.java
+++
b/server/src/test/java/org/apache/gravitino/server/web/rest/TestMetadataObjectCredentialOperations.java
@@ -19,7 +19,10 @@
package org.apache.gravitino.server.web.rest;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.mockStatic;
+import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import java.io.IOException;
@@ -28,6 +31,8 @@ import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.core.Application;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.reflect.FieldUtils;
+import org.apache.gravitino.Entity;
import org.apache.gravitino.MetadataObject;
import org.apache.gravitino.MetadataObjects;
import org.apache.gravitino.credential.Credential;
@@ -37,12 +42,15 @@ import
org.apache.gravitino.dto.responses.CredentialResponse;
import org.apache.gravitino.dto.responses.ErrorResponse;
import org.apache.gravitino.dto.util.DTOConverters;
import org.apache.gravitino.rest.RESTUtils;
+import org.apache.gravitino.server.authorization.MetadataAuthzHelper;
+import
org.apache.gravitino.server.authorization.expression.AuthorizationExpressionConstants;
import org.glassfish.jersey.internal.inject.AbstractBinder;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.test.JerseyTest;
import org.glassfish.jersey.test.TestProperties;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.mockito.MockedStatic;
public class TestMetadataObjectCredentialOperations extends JerseyTest {
@@ -84,6 +92,78 @@ public class TestMetadataObjectCredentialOperations extends
JerseyTest {
return resourceConfig;
}
+ /** Checks catalog secret privileges without changing fileset authorization.
*/
+ @Test
+ public void testCatalogCredentialsRequireBothSecretPrivileges() throws
Exception {
+ for (boolean useSecrets : new boolean[] {false, true}) {
+ for (boolean includeCredentials : new boolean[] {false, true}) {
+ CredentialOperationDispatcher dispatcher =
mock(CredentialOperationDispatcher.class);
+ MetadataObjectCredentialOperations operations =
+ new MetadataObjectCredentialOperations(dispatcher);
+ FieldUtils.writeField(operations, "httpRequest",
mock(HttpServletRequest.class), true);
+ try (MockedStatic<MetadataAuthzHelper> auth =
mockStatic(MetadataAuthzHelper.class)) {
+ auth.when(
+ () ->
+ MetadataAuthzHelper.checkAccess(
+ any(),
+ any(Entity.EntityType.class),
+ eq(
+ AuthorizationExpressionConstants
+
.FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION)))
+ .thenReturn(useSecrets);
+ auth.when(
+ () ->
+ MetadataAuthzHelper.checkAccess(
+ any(),
+ any(Entity.EntityType.class),
+ eq(
+ AuthorizationExpressionConstants
+
.FILTER_INCLUDE_CREDENTIAL_SECRETS_AUTHORIZATION_EXPRESSION)))
+ .thenReturn(includeCredentials);
+ try (Response response = operations.getCredentials("test",
"catalog", "catalog")) {
+ Assertions.assertEquals(
+ useSecrets && includeCredentials ? 200 : 403,
response.getStatus());
+ }
+ if (!useSecrets || !includeCredentials)
verifyNoInteractions(dispatcher);
+ try (Response response =
+ operations.getCredentials("test", "fileset",
"catalog.schema.fileset")) {
+ Assertions.assertEquals(200, response.getStatus());
+ }
+ }
+ }
+ }
+ }
+
+ /** Checks credential client errors identify the requested object. */
+ @Test
+ public void testUnsupportedObjectAndProviderErrorsIdentifyTheObject() {
+ Response unsupported =
+ target(basePath(metalake))
+ .path("table")
+ .path("catalog.schema.table")
+ .path("credentials")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+ Assertions.assertEquals(400, unsupported.getStatus());
+ String message = unsupported.readEntity(ErrorResponse.class).getMessage();
+ Assertions.assertTrue(message.contains("catalog.schema.table"));
+ Assertions.assertTrue(message.contains("TABLE"));
+ when(credentialOperationDispatcher.getCredentials(any(), any()))
+ .thenThrow(new IllegalArgumentException("Invalid provider"));
+ Response invalid =
+ target(basePath(metalake))
+ .path("fileset")
+ .path("catalog.schema.fileset")
+ .path("credentials")
+ .request(MediaType.APPLICATION_JSON_TYPE)
+ .accept("application/vnd.gravitino.v1+json")
+ .get();
+ Assertions.assertEquals(400, invalid.getStatus());
+ Assertions.assertTrue(
+
invalid.readEntity(ErrorResponse.class).getMessage().contains("catalog.schema.fileset"));
+ }
+
@Test
public void testGetCredentialsForCatalog() {
testGetCredentialsForObject(MetadataObjects.parse("catalog",
MetadataObject.Type.CATALOG));
diff --git
a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkAuthorizationIT.java
b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkAuthorizationIT.java
index 8e7e0b6d0a..c2b75fa105 100644
---
a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkAuthorizationIT.java
+++
b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkAuthorizationIT.java
@@ -22,6 +22,7 @@ import static org.junit.Assert.assertThrows;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
+import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import java.io.IOException;
import java.sql.SQLException;
@@ -157,8 +158,9 @@ public abstract class SparkAuthorizationIT extends BaseIT {
Privileges.UseSchema.allow(),
Privileges.SelectTable.allow(),
Privileges.CreateTable.allow(),
- // Spark JDBC catalog needs USE_SECRETS to receive vended jdbc
credentials.
- Privileges.UseSecrets.allow()));
+ // Spark JDBC needs both secret privileges to receive catalog
credentials.
+ Privileges.UseSecrets.allow(),
+ Privileges.IncludeCredentialSecrets.allow()));
gravitinoMetalake.createRole(ROLE, new HashMap<>(),
ImmutableList.of(securableObject));
gravitinoMetalake.grantRolesToUser(ImmutableList.of(ROLE), NORMAL_USER);
}
@@ -183,6 +185,34 @@ public abstract class SparkAuthorizationIT extends BaseIT {
.getOrCreate();
}
+ /** Verifies Spark cannot initialize a JDBC catalog with either secret
privilege missing. */
+ @Test
+ @Order(0)
+ public void testCatalogRequiresBothCredentialPrivileges() {
+ GravitinoMetalake metalake = client.loadMetalake(METALAKE);
+ MetadataObject catalog =
+ MetadataObjects.of(ImmutableList.of(JDBC_CATALOG),
MetadataObject.Type.CATALOG);
+ try {
+ metalake.revokePrivilegesFromRole(
+ ROLE, catalog, ImmutableSet.of(Privileges.UseSecrets.allow()));
+ assertThrows(
+ ForbiddenException.class, () -> normalUserSparkSession.sql("USE " +
JDBC_CATALOG));
+
+ metalake.grantPrivilegesToRole(
+ ROLE, catalog, ImmutableList.of(Privileges.UseSecrets.allow()));
+ metalake.revokePrivilegesFromRole(
+ ROLE, catalog,
ImmutableSet.of(Privileges.IncludeCredentialSecrets.allow()));
+ assertThrows(
+ ForbiddenException.class, () -> normalUserSparkSession.sql("USE " +
JDBC_CATALOG));
+ } finally {
+ metalake.grantPrivilegesToRole(
+ ROLE,
+ catalog,
+ ImmutableList.of(
+ Privileges.UseSecrets.allow(),
Privileges.IncludeCredentialSecrets.allow()));
+ }
+ }
+
@Test
@Order(1)
public void testCreateTable() {
@@ -286,7 +316,10 @@ public abstract class SparkAuthorizationIT extends BaseIT {
SecurableObject catalogObject =
SecurableObjects.ofCatalog(
JDBC_CATALOG,
- ImmutableList.of(Privileges.UseCatalog.allow(),
Privileges.UseSecrets.allow()));
+ ImmutableList.of(
+ Privileges.UseCatalog.allow(),
+ Privileges.UseSecrets.allow(),
+ Privileges.IncludeCredentialSecrets.allow()));
SecurableObject schemaObject =
SecurableObjects.ofSchema(
catalogObject,
@@ -336,7 +369,8 @@ public abstract class SparkAuthorizationIT extends BaseIT {
Privileges.UseSchema.allow(),
Privileges.SelectTable.allow(),
Privileges.CreateTable.allow(),
- Privileges.UseSecrets.allow()));
+ Privileges.UseSecrets.allow(),
+ Privileges.IncludeCredentialSecrets.allow()));
gravitinoMetalake.createRole(testRole, new HashMap<>(),
ImmutableList.of(catalogObject));
gravitinoMetalake.grantRolesToUser(ImmutableList.of(testRole),
NORMAL_USER);
diff --git
a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkJwksAuthorizationIT.java
b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkJwksAuthorizationIT.java
index 2b2aecaae6..2cd01398ee 100644
---
a/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkJwksAuthorizationIT.java
+++
b/spark-connector/spark-common/src/test/java/org/apache/gravitino/spark/connector/integration/test/authorization/SparkJwksAuthorizationIT.java
@@ -197,8 +197,9 @@ public abstract class SparkJwksAuthorizationIT extends
BaseIT {
Privileges.UseSchema.allow(),
Privileges.CreateTable.allow(),
Privileges.SelectTable.allow(),
- // Spark JDBC needs USE_SECRETS to receive vended jdbc
credentials.
- Privileges.UseSecrets.allow()));
+ // Spark JDBC needs both secret privileges to receive catalog
credentials.
+ Privileges.UseSecrets.allow(),
+ Privileges.IncludeCredentialSecrets.allow()));
metalake.createRole(ALICE_ROLE, new HashMap<>(),
ImmutableList.of(catalogAccess));
metalake.grantRolesToUser(ImmutableList.of(ALICE_ROLE), ALICE);
}
@@ -253,6 +254,9 @@ public abstract class SparkJwksAuthorizationIT extends
BaseIT {
GravitinoMetalake bobMetalake = bobClient.loadMetalake(METALAKE);
Catalog catalog = bobMetalake.loadCatalog(CATALOG);
Assertions.assertNotNull(catalog);
+ // Metadata visibility does not grant Bob the source account's credentials.
+ Assertions.assertThrows(
+ ForbiddenException.class, () ->
catalog.supportsCredentials().getCredentials());
boolean tableExists =
catalog.asTableCatalog().tableExists(NameIdentifier.of(SCHEMA,
ALICE_TABLE));