This is an automated email from the ASF dual-hosted git repository.
yuqi1129 pushed a commit to branch branch-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git
The following commit(s) were added to refs/heads/branch-1.3 by this push:
new ebbfc2e1c1 [Cherry-pick to branch-1.3] [#14638] fix(jdbc): protect
catalog credentials and reject URL secrets (#14639) (#14678)
ebbfc2e1c1 is described below
commit ebbfc2e1c115d8dbd9fef6418dcc8e5ee7aa36e7
Author: github-actions[bot]
<41898282+github-actions[bot]@users.noreply.github.com>
AuthorDate: Fri Nov 6 11:21:06 2026 +0800
[Cherry-pick to branch-1.3] [#14638] fix(jdbc): protect catalog credentials
and reject URL secrets (#14639) (#14678)
### What changes were proposed in this pull request?
Resolve the conflicted cherry-pick of
922ed72173d9f153286a9cf30c5fc9c716c4520c (#14639) onto `branch-1.3`.
- Keep the catalog credential guard, JDBC URL credential rejection, HTTP
error handling, and corresponding regression tests.
- Add the two required credential privileges to the 1.3 Java/Python
factories, CLI, and authorization expressions, preserving their
main-branch bit positions. They bind to metalakes/catalogs on this
branch; explicit denies override grants, with the existing
metalake-owner exception.
- Apply legacy JDBC URL masking in 1.3's actual
`BaseCatalog.properties()` path, including credential backfill. Adapt
the URL scanner to the branch's Java 8 API target while preserving its
existing malformed-URL validation behavior.
- Preserve the branch's direct fileset credential path. Main-only
Secrets API helpers, GVFS catalog overlays, and class-loader cache keys
are not introduced.
### Why are the changes needed?
The automatic cherry-pick left conflict markers and references to APIs
absent from 1.3. The backport must retain the credential protections
without importing unrelated main-branch features.
### Does this PR introduce _any_ user-facing change?
Catalog credential access now requires metadata access plus both
`USE_SECRETS` and `INCLUDE_CREDENTIAL_SECRETS`, or metalake ownership.
The two privileges are new to 1.3; use matching clients/CLI to grant
them. Fileset path authorization is unchanged, and this does not add a
Secrets API.
Move credentials out of relational catalogs' `jdbc-url` into
`jdbc-user`/`jdbc-password` before upgrading. Legacy credential-bearing
URLs are masked if they reach the property-read path. JDBC-backed
Iceberg/Paimon `uri` values remain outside this URL protection. No store
schema or dependency change is introduced.
Catalog credential authorization retains separate request contexts for
the two added checks. This adds bounded repeated owner/user/role
lookups; consolidating request contexts is outside this security
backport.
### How was this patch tested?
122 targeted Java tests and 45 Python privilege/DTO tests passed, with
zero failures/errors/skips. Coverage includes privilege factories and
bit compatibility, both grants, missing grants, cross-scope denies,
owner exceptions, REST refusals, encoded JDBC URLs, native Connector/J
parsing, and masking with/without credential backfill.
Spark 3.5 and Hadoop GVFS test sources compile. Scoped Spotless, Black,
Pylint, and `git diff --check` passed. `:docs:build` passed. Disabling
the catalog guard and URL masking caused three regression cases to fail;
restoring the candidate made all nine cases in those two classes pass
again.
Full core, live Spark/MySQL integration, and cloud fileset integration
suites were not run for this backport.
---------
Co-authored-by: Qi Yu <[email protected]>
---
.../apache/gravitino/authorization/Privilege.java | 6 +-
.../apache/gravitino/authorization/Privileges.java | 79 ++++++++++++
.../gravitino/credential/SupportsCredentials.java | 9 ++
.../TestCatalogCredentialPrivileges.java | 54 +++++++++
.../gravitino/catalog/jdbc/config/JdbcConfig.java | 8 +-
.../catalog/jdbc/config/TestJdbcConfig.java | 13 ++
.../catalog/mysql/TestMysqlJdbcUrlCredentials.java | 80 +++++++++++++
.../java/org/apache/gravitino/cli/Privileges.java | 10 ++
.../cli/TestCatalogCredentialPrivileges.java | 23 ++--
.../gravitino/api/authorization/privileges.py | 66 +++++++++++
.../api/credential/supports_credentials.py | 9 ++
.../unittests/authorization/test_privileges.py | 21 ++++
.../FilesetCatalogAuthorizationCredentialIT.java | 40 ++++---
.../org/apache/gravitino/utils/JdbcUrlUtils.java | 75 ++++++++++++
.../apache/gravitino/utils/TestJdbcUrlUtils.java | 55 +++++++++
.../apache/gravitino/connector/BaseCatalog.java | 11 ++
.../apache/gravitino/catalog/TestBaseCatalog.java | 31 +++++
docs/aws-glue-catalog.md | 2 +-
docs/lakehouse-paimon-catalog.md | 2 +-
docs/open-api/credentials.yaml | 12 ++
docs/security/access-control.md | 8 +-
docs/security/credential-vending.md | 23 ++++
.../AuthorizationExpressionConstants.java | 15 +++
.../TestCatalogCredentialAuthorization.java | 132 +++++++++++++++++++++
.../server/web/rest/ExceptionHandlers.java | 5 +-
.../rest/MetadataObjectCredentialOperations.java | 24 +++-
.../TestMetadataObjectCredentialOperations.java | 80 +++++++++++++
.../test/authorization/SparkAuthorizationIT.java | 45 ++++++-
.../authorization/SparkJwksAuthorizationIT.java | 8 +-
29 files changed, 906 insertions(+), 40 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 69e1392d69..2c0219a52e 100644
--- a/api/src/main/java/org/apache/gravitino/authorization/Privilege.java
+++ b/api/src/main/java/org/apache/gravitino/authorization/Privilege.java
@@ -151,7 +151,11 @@ public interface Privilege {
/** The privilege to execute (invoke) a function. */
EXECUTE_FUNCTION(0L, 1L << 31),
/** The privilege to alter a function's metadata. */
- MODIFY_FUNCTION(0L, 1L << 32);
+ MODIFY_FUNCTION(0L, 1L << 32),
+ /** Required together with INCLUDE_CREDENTIAL_SECRETS for catalog
credential access. */
+ USE_SECRETS(0L, 1L << 37),
+ /** Required together with USE_SECRETS for catalog credential access. */
+ INCLUDE_CREDENTIAL_SECRETS(0L, 1L << 38);
private final long highBits;
private final long lowBits;
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 393252cf15..8b81a1bfdc 100644
--- a/api/src/main/java/org/apache/gravitino/authorization/Privileges.java
+++ b/api/src/main/java/org/apache/gravitino/authorization/Privileges.java
@@ -113,6 +113,10 @@ public class Privileges {
return CreateCatalog.allow();
case USE_CATALOG:
return UseCatalog.allow();
+ case USE_SECRETS:
+ return UseSecrets.allow();
+ case INCLUDE_CREDENTIAL_SECRETS:
+ return IncludeCredentialSecrets.allow();
// Schema
case CREATE_SCHEMA:
@@ -235,6 +239,10 @@ public class Privileges {
return CreateCatalog.deny();
case USE_CATALOG:
return UseCatalog.deny();
+ case USE_SECRETS:
+ return UseSecrets.deny();
+ case INCLUDE_CREDENTIAL_SECRETS:
+ return IncludeCredentialSecrets.deny();
// Schema
case CREATE_SCHEMA:
@@ -1244,6 +1252,77 @@ public class Privileges {
}
}
+ /**
+ * Required together with {@link IncludeCredentialSecrets} for catalog
{@code getCredentials}, in
+ * addition to metadata access. Metalake owners are exempt. Fileset path
authorization is
+ * unchanged. This branch supports binding this privilege to metalakes and
catalogs.
+ */
+ public static final class UseSecrets extends GenericPrivilege<UseSecrets> {
+ private static final UseSecrets ALLOW_INSTANCE =
+ new UseSecrets(Condition.ALLOW, Name.USE_SECRETS);
+ private static final UseSecrets DENY_INSTANCE =
+ new UseSecrets(Condition.DENY, Name.USE_SECRETS);
+
+ private UseSecrets(Condition condition, Name name) {
+ super(condition, name);
+ }
+
+ /**
+ * @return the instance with allow condition
+ */
+ public static UseSecrets allow() {
+ return ALLOW_INSTANCE;
+ }
+
+ /**
+ * @return the instance with deny condition
+ */
+ public static UseSecrets deny() {
+ return DENY_INSTANCE;
+ }
+
+ @Override
+ public boolean canBindTo(MetadataObject.Type type) {
+ return type == MetadataObject.Type.METALAKE || type ==
MetadataObject.Type.CATALOG;
+ }
+ }
+
+ /**
+ * Required together with {@link UseSecrets} for catalog {@code
getCredentials}, in addition to
+ * metadata access. Metalake owners are exempt. Fileset path authorization
is unchanged. This
+ * branch supports binding this privilege to metalakes and catalogs.
+ */
+ public static final class IncludeCredentialSecrets
+ extends GenericPrivilege<IncludeCredentialSecrets> {
+ private static final IncludeCredentialSecrets ALLOW_INSTANCE =
+ new IncludeCredentialSecrets(Condition.ALLOW,
Name.INCLUDE_CREDENTIAL_SECRETS);
+ private static final IncludeCredentialSecrets DENY_INSTANCE =
+ new IncludeCredentialSecrets(Condition.DENY,
Name.INCLUDE_CREDENTIAL_SECRETS);
+
+ private IncludeCredentialSecrets(Condition condition, Name name) {
+ super(condition, name);
+ }
+
+ /**
+ * @return the instance with allow condition
+ */
+ public static IncludeCredentialSecrets allow() {
+ return ALLOW_INSTANCE;
+ }
+
+ /**
+ * @return the instance with deny condition
+ */
+ public static IncludeCredentialSecrets deny() {
+ return DENY_INSTANCE;
+ }
+
+ @Override
+ public boolean canBindTo(MetadataObject.Type type) {
+ return type == MetadataObject.Type.METALAKE || type ==
MetadataObject.Type.CATALOG;
+ }
+ }
+
/** The privilege to register a job template. */
public static class RegisterJobTemplate extends
GenericPrivilege<RegisterJobTemplate> {
private static final RegisterJobTemplate ALLOW_INSTANCE =
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/api/src/test/java/org/apache/gravitino/authorization/TestCatalogCredentialPrivileges.java
b/api/src/test/java/org/apache/gravitino/authorization/TestCatalogCredentialPrivileges.java
new file mode 100644
index 0000000000..2bb1dc901e
--- /dev/null
+++
b/api/src/test/java/org/apache/gravitino/authorization/TestCatalogCredentialPrivileges.java
@@ -0,0 +1,54 @@
+/*
+ * 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.authorization;
+
+import org.apache.gravitino.MetadataObject;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+class TestCatalogCredentialPrivileges {
+ @Test
+ void testFactoriesAndBindings() {
+ for (Privilege.Name name :
+ new Privilege.Name[] {
+ Privilege.Name.USE_SECRETS, Privilege.Name.INCLUDE_CREDENTIAL_SECRETS
+ }) {
+ Privilege allow = Privileges.allow(name.name());
+ Privilege deny = Privileges.deny(name.name());
+ Assertions.assertEquals(name, allow.name());
+ Assertions.assertEquals(name, deny.name());
+ Assertions.assertEquals(Privilege.Condition.ALLOW, allow.condition());
+ Assertions.assertEquals(Privilege.Condition.DENY, deny.condition());
+ for (MetadataObject.Type type : MetadataObject.Type.values()) {
+ boolean supported =
+ type == MetadataObject.Type.METALAKE || type ==
MetadataObject.Type.CATALOG;
+ Assertions.assertEquals(supported, allow.canBindTo(type));
+ Assertions.assertEquals(supported, deny.canBindTo(type));
+ }
+ }
+ }
+
+ @Test
+ void testBitsMatchMainBranch() {
+ Assertions.assertEquals(1L << 37, Privilege.Name.USE_SECRETS.getLowBits());
+ Assertions.assertEquals(1L << 38,
Privilege.Name.INCLUDE_CREDENTIAL_SECRETS.getLowBits());
+ Assertions.assertEquals(0L, Privilege.Name.USE_SECRETS.getHighBits());
+ Assertions.assertEquals(0L,
Privilege.Name.INCLUDE_CREDENTIAL_SECRETS.getHighBits());
+ }
+}
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 435fe832eb..b9936ca5d5 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 {
@@ -149,7 +150,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 194f82a76b..389c5aea7b 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-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/cli/src/main/java/org/apache/gravitino/cli/Privileges.java
b/clients/cli/src/main/java/org/apache/gravitino/cli/Privileges.java
index 2f6ab79192..737a64b808 100644
--- a/clients/cli/src/main/java/org/apache/gravitino/cli/Privileges.java
+++ b/clients/cli/src/main/java/org/apache/gravitino/cli/Privileges.java
@@ -31,6 +31,10 @@ public class Privileges {
public static final String CREATE_CATALOG = "create_catalog";
/** Represents the privilege to use a catalog. */
public static final String USE_CATALOG = "use_catalog";
+ /** Required with INCLUDE_CREDENTIAL_SECRETS for catalog credential access.
*/
+ public static final String USE_SECRETS = "use_secrets";
+ /** Required with USE_SECRETS for catalog credential access. */
+ public static final String INCLUDE_CREDENTIAL_SECRETS =
"include_credential_secrets";
/** Represents the privilege to create a schema. */
public static final String CREATE_SCHEMA = "create_schema";
/** Represents the privilege to use a schema. */
@@ -65,6 +69,8 @@ public class Privileges {
static {
VALID_PRIVILEGES.add(CREATE_CATALOG);
VALID_PRIVILEGES.add(USE_CATALOG);
+ VALID_PRIVILEGES.add(USE_SECRETS);
+ VALID_PRIVILEGES.add(INCLUDE_CREDENTIAL_SECRETS);
VALID_PRIVILEGES.add(CREATE_SCHEMA);
VALID_PRIVILEGES.add(USE_SCHEMA);
VALID_PRIVILEGES.add(CREATE_TABLE);
@@ -103,6 +109,10 @@ public class Privileges {
return Privilege.Name.CREATE_CATALOG;
case USE_CATALOG:
return Privilege.Name.USE_CATALOG;
+ case USE_SECRETS:
+ return Privilege.Name.USE_SECRETS;
+ case INCLUDE_CREDENTIAL_SECRETS:
+ return Privilege.Name.INCLUDE_CREDENTIAL_SECRETS;
case CREATE_SCHEMA:
return Privilege.Name.CREATE_SCHEMA;
case USE_SCHEMA:
diff --git
a/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/config/TestJdbcConfig.java
b/clients/cli/src/test/java/org/apache/gravitino/cli/TestCatalogCredentialPrivileges.java
similarity index 62%
copy from
catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/config/TestJdbcConfig.java
copy to
clients/cli/src/test/java/org/apache/gravitino/cli/TestCatalogCredentialPrivileges.java
index 194f82a76b..1cae21aa06 100644
---
a/catalogs/catalog-jdbc-common/src/test/java/org/apache/gravitino/catalog/jdbc/config/TestJdbcConfig.java
+++
b/clients/cli/src/test/java/org/apache/gravitino/cli/TestCatalogCredentialPrivileges.java
@@ -16,19 +16,24 @@
* specific language governing permissions and limitations
* under the License.
*/
-package org.apache.gravitino.catalog.jdbc.config;
-import com.google.common.collect.Maps;
-import java.util.HashMap;
+package org.apache.gravitino.cli;
+
+import java.util.Locale;
+import org.apache.gravitino.authorization.Privilege;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
-public class TestJdbcConfig {
-
+class TestCatalogCredentialPrivileges {
@Test
- public void testCreateDataSourceConfig() {
- HashMap<String, String> properties = Maps.newHashMap();
- properties.put(JdbcConfig.JDBC_URL.getKey(), "jdbc:sqlite::memory:");
- Assertions.assertDoesNotThrow(() -> new JdbcConfig(properties));
+ void testCredentialGrantsAreAcceptedByCli() {
+ for (Privilege.Name name :
+ new Privilege.Name[] {
+ Privilege.Name.USE_SECRETS, Privilege.Name.INCLUDE_CREDENTIAL_SECRETS
+ }) {
+ String option = name.name().toLowerCase(Locale.ROOT);
+ Assertions.assertTrue(Privileges.isValid(option));
+ Assertions.assertEquals(name, Privileges.toName(option));
+ }
}
}
diff --git a/clients/client-python/gravitino/api/authorization/privileges.py
b/clients/client-python/gravitino/api/authorization/privileges.py
index fde10d00e9..3229a5002c 100644
--- a/clients/client-python/gravitino/api/authorization/privileges.py
+++ b/clients/client-python/gravitino/api/authorization/privileges.py
@@ -192,6 +192,12 @@ class Privilege(ABC):
MODIFY_FUNCTION = (0, 1 << 32)
"""The privilege to alter a function's metadata."""
+ USE_SECRETS = (0, 1 << 37)
+ """Required with INCLUDE_CREDENTIAL_SECRETS for catalog credentials."""
+
+ INCLUDE_CREDENTIAL_SECRETS = (0, 1 << 38)
+ """Required with USE_SECRETS for catalog credentials."""
+
def __init__(self, high_bits: int, low_bits: int) -> None:
"""
Initialize the Name with the high and low bits.
@@ -1586,10 +1592,70 @@ class ModifyFunction(GenericPrivilege):
return obj_type in Privileges.FUNCTION_SUPPORTED_TYPES
+class UseSecrets(GenericPrivilege):
+ """Required with INCLUDE_CREDENTIAL_SECRETS for catalog credentials,
unless metalake owner.
+
+ Supports metalake and catalog grants on this branch; fileset access is
unchanged.
+ """
+
+ _ALLOW_INSTANCE: Optional["UseSecrets"] = None
+ _DENY_INSTANCE: Optional["UseSecrets"] = None
+
+ @staticmethod
+ def allow() -> Privilege:
+ if UseSecrets._ALLOW_INSTANCE is None:
+ UseSecrets._ALLOW_INSTANCE = UseSecrets(
+ Privilege.Condition.ALLOW, Privilege.Name.USE_SECRETS
+ )
+ return UseSecrets._ALLOW_INSTANCE
+
+ @staticmethod
+ def deny() -> Privilege:
+ if UseSecrets._DENY_INSTANCE is None:
+ UseSecrets._DENY_INSTANCE = UseSecrets(
+ Privilege.Condition.DENY, Privilege.Name.USE_SECRETS
+ )
+ return UseSecrets._DENY_INSTANCE
+
+ def can_bind_to(self, obj_type: MetadataObject.Type) -> bool:
+ return obj_type in {MetadataObject.Type.METALAKE,
MetadataObject.Type.CATALOG}
+
+
+class IncludeCredentialSecrets(GenericPrivilege):
+ """Required with USE_SECRETS for catalog credentials, unless metalake
owner.
+
+ Supports metalake and catalog grants on this branch; fileset access is
unchanged.
+ """
+
+ _ALLOW_INSTANCE: Optional["IncludeCredentialSecrets"] = None
+ _DENY_INSTANCE: Optional["IncludeCredentialSecrets"] = None
+
+ @staticmethod
+ def allow() -> Privilege:
+ if IncludeCredentialSecrets._ALLOW_INSTANCE is None:
+ IncludeCredentialSecrets._ALLOW_INSTANCE =
IncludeCredentialSecrets(
+ Privilege.Condition.ALLOW,
Privilege.Name.INCLUDE_CREDENTIAL_SECRETS
+ )
+ return IncludeCredentialSecrets._ALLOW_INSTANCE
+
+ @staticmethod
+ def deny() -> Privilege:
+ if IncludeCredentialSecrets._DENY_INSTANCE is None:
+ IncludeCredentialSecrets._DENY_INSTANCE = IncludeCredentialSecrets(
+ Privilege.Condition.DENY,
Privilege.Name.INCLUDE_CREDENTIAL_SECRETS
+ )
+ return IncludeCredentialSecrets._DENY_INSTANCE
+
+ def can_bind_to(self, obj_type: MetadataObject.Type) -> bool:
+ return obj_type in {MetadataObject.Type.METALAKE,
MetadataObject.Type.CATALOG}
+
+
class Privileges:
_PRIVILEGE_TYPES = {
Privilege.Name.CREATE_CATALOG: CreateCatalog,
Privilege.Name.USE_CATALOG: UseCatalog,
+ Privilege.Name.USE_SECRETS: UseSecrets,
+ Privilege.Name.INCLUDE_CREDENTIAL_SECRETS: IncludeCredentialSecrets,
Privilege.Name.CREATE_SCHEMA: CreateSchema,
Privilege.Name.USE_SCHEMA: UseSchema,
Privilege.Name.CREATE_TABLE: CreateTable,
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/tests/unittests/authorization/test_privileges.py
b/clients/client-python/tests/unittests/authorization/test_privileges.py
index daa3317989..277792280f 100644
--- a/clients/client-python/tests/unittests/authorization/test_privileges.py
+++ b/clients/client-python/tests/unittests/authorization/test_privileges.py
@@ -60,6 +60,27 @@ from gravitino.exceptions.base import
IllegalArgumentException
class TestPrivileges(unittest.TestCase):
+ def test_catalog_credential_privileges(self):
+ for name in (
+ Privilege.Name.USE_SECRETS,
+ Privilege.Name.INCLUDE_CREDENTIAL_SECRETS,
+ ):
+ for factory, condition in (
+ (Privileges.allow, Privilege.Condition.ALLOW),
+ (Privileges.deny, Privilege.Condition.DENY),
+ ):
+ privilege = factory(name.name)
+ self.assertEqual(name, privilege.name())
+ self.assertEqual(condition, privilege.condition())
+ for obj_type in MetadataObject.Type:
+ self.assertEqual(
+ obj_type
+ in {MetadataObject.Type.METALAKE,
MetadataObject.Type.CATALOG},
+ privilege.can_bind_to(obj_type),
+ )
+ self.assertEqual((0, 1 << 37), Privilege.Name.USE_SECRETS.value)
+ self.assertEqual((0, 1 << 38),
Privilege.Name.INCLUDE_CREDENTIAL_SECRETS.value)
+
def test_allow_and_deny_return_instances_for_all_privileges(self) -> None:
for name in Privilege.Name:
with self.subTest(privilege=name.name):
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 b451ed7507..30b39561f3 100644
--- a/common/src/main/java/org/apache/gravitino/utils/JdbcUrlUtils.java
+++ b/common/src/main/java/org/apache/gravitino/utils/JdbcUrlUtils.java
@@ -22,6 +22,7 @@ package org.apache.gravitino.utils;
import com.google.common.base.Preconditions;
import java.io.IOException;
import java.io.StringReader;
+import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Collections;
@@ -31,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;
@@ -42,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.
@@ -74,6 +87,51 @@ 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.
+ if (USER_INFO.matcher(url).find()) {
+ return true;
+ }
+ String form = lowerUrl;
+ // Inspect each decoding stage. Sanitize malformed escapes on every pass
so they cannot
+ // hide a separately encoded credential parameter. Keep the existing URL
validator unchanged.
+ for (int depth = 0; depth <= 5; depth++) {
+ if (containsCredentialParameters(form, mysqlUrl)) {
+ return true;
+ }
+ if (depth == 5) {
+ break;
+ }
+ String decoded;
+ try {
+ decoded =
+ URLDecoder.decode(form.replaceAll("%(?![0-9a-fA-F]{2})", "%25"),
"UTF-8")
+ .toLowerCase(Locale.ROOT);
+ } catch (UnsupportedEncodingException e) {
+ // UTF-8 is required by the JVM specification.
+ throw new IllegalStateException(e);
+ }
+ if (decoded.equals(form)) {
+ break;
+ }
+ form = decoded;
+ }
+ return false;
+ }
+
/**
* Validates the JDBC configuration by checking the driver and URL for
unsafe parameters.
*
@@ -118,6 +176,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 056178ca72..c17b7a1d85 100644
--- a/common/src/test/java/org/apache/gravitino/utils/TestJdbcUrlUtils.java
+++ b/common/src/test/java/org/apache/gravitino/utils/TestJdbcUrlUtils.java
@@ -27,8 +27,63 @@ 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:postgresql://host/db?%2570assword=hidden#%25zz",
+ "jdbc:postgresql://host/db?%252570assword=hidden#%2525zz",
+ "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:postgresql://host/db?applicationName=100%",
+ "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_ShouldThrowGravitinoRuntimeException() {
diff --git a/core/src/main/java/org/apache/gravitino/connector/BaseCatalog.java
b/core/src/main/java/org/apache/gravitino/connector/BaseCatalog.java
index e373ef717a..6050a4e9c3 100644
--- a/core/src/main/java/org/apache/gravitino/connector/BaseCatalog.java
+++ b/core/src/main/java/org/apache/gravitino/connector/BaseCatalog.java
@@ -59,6 +59,7 @@ import org.apache.gravitino.storage.GCSProperties;
import org.apache.gravitino.storage.OSSProperties;
import org.apache.gravitino.storage.S3Properties;
import org.apache.gravitino.utils.IsolatedClassLoader;
+import org.apache.gravitino.utils.JdbcUrlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -576,6 +577,7 @@ public abstract class BaseCatalog<T extends BaseCatalog>
}
}
+ maskJdbcUrlCredentials(tempProperties);
properties = tempProperties;
}
}
@@ -585,6 +587,7 @@ public abstract class BaseCatalog<T extends BaseCatalog>
}
Map<String, String> result = Maps.newHashMap(properties);
result.putAll(propertiesWithCredentialProviders());
+ maskJdbcUrlCredentials(result);
return result;
}
@@ -673,4 +676,12 @@ public abstract class BaseCatalog<T extends BaseCatalog>
private CatalogOperations asProxyOps(CatalogOperations ops, ProxyPlugin
plugin) {
return OperationsProxy.createProxy(ops, plugin);
}
+
+ private static void maskJdbcUrlCredentials(Map<String, String> properties) {
+ properties.replaceAll(
+ (key, value) ->
+ "jdbc-url".equalsIgnoreCase(key) &&
JdbcUrlUtils.containsCredentials(value)
+ ? "******"
+ : value);
+ }
}
diff --git
a/core/src/test/java/org/apache/gravitino/catalog/TestBaseCatalog.java
b/core/src/test/java/org/apache/gravitino/catalog/TestBaseCatalog.java
index 917d3b314a..ddb8ccad14 100644
--- a/core/src/test/java/org/apache/gravitino/catalog/TestBaseCatalog.java
+++ b/core/src/test/java/org/apache/gravitino/catalog/TestBaseCatalog.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.catalog;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
+import java.util.Map;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.apache.gravitino.TestCatalog;
import org.apache.gravitino.connector.BaseCatalog;
@@ -31,10 +32,40 @@ import
org.apache.gravitino.credential.CatalogCredentialManager;
import org.apache.gravitino.meta.CatalogEntity;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.Mockito;
public class TestBaseCatalog {
+ @ParameterizedTest
+ @ValueSource(booleans = {false, true})
+ void testLegacyJdbcUrlsAreMaskedWithAndWithoutBackfill(boolean backfill) {
+ for (String url :
+ new String[] {
+ "jdbc:mysql://localhost/db?password=source-secret",
+ "jdbc:mysql://user:encoded%2Fsecret@localhost/db",
+ "jdbc:postgresql://localhost/db?%70assword=source-secret",
+ "jdbc:mysql://localhost/db?passwordCharacterEncoding=UTF-8"
+ }) {
+ CatalogEntity entity = Mockito.mock(CatalogEntity.class);
+ Map<String, String> raw = Map.of("JDBC-URL", url, "ordinary", "visible");
+ Mockito.when(entity.getProperties()).thenReturn(raw);
+ TestCatalog catalog =
+ new TestCatalog() {
+ @Override
+ protected boolean shouldBackfillCredential() {
+ return backfill;
+ }
+ }.withCatalogEntity(entity);
+ String expected = url.endsWith("UTF-8") ? url : "******";
+ Assertions.assertEquals(expected, catalog.properties().get("JDBC-URL"));
+ Assertions.assertEquals(expected, catalog.properties().get("JDBC-URL"));
+ Assertions.assertEquals("visible", catalog.properties().get("ordinary"));
+ Assertions.assertEquals(url, entity.getProperties().get("JDBC-URL"));
+ }
+ }
+
@Test
void testCustomCatalogOperations() {
CatalogEntity entity = Mockito.mock(CatalogEntity.class);
diff --git a/docs/aws-glue-catalog.md b/docs/aws-glue-catalog.md
index 87b98a7a06..6c90a71bc7 100644
--- a/docs/aws-glue-catalog.md
+++ b/docs/aws-glue-catalog.md
@@ -62,7 +62,7 @@ Besides the [common catalog
properties](./gravitino-server-config.md#catalog-pro
Refer to [Manage Catalogs and
Schemas](./manage-catalogs-and-schemas.md#catalog-operations) for more details.
:::note
-Sensitive catalog properties such as `aws-access-key-id` and
`aws-secret-access-key` are hidden from the load catalog response. Use the
[credential vending API](security/credential-vending.md) to retrieve them at
runtime.
+Sensitive catalog properties such as `aws-access-key-id` and
`aws-secret-access-key` are hidden from the load catalog response. Use the
[credential vending API](security/credential-vending.md) to retrieve them at
runtime. Catalog credential access requires metadata access plus both
`USE_SECRETS` and `INCLUDE_CREDENTIAL_SECRETS`, or metalake ownership.
:::
## Schema
diff --git a/docs/lakehouse-paimon-catalog.md b/docs/lakehouse-paimon-catalog.md
index e398c5e5b4..41360ba315 100644
--- a/docs/lakehouse-paimon-catalog.md
+++ b/docs/lakehouse-paimon-catalog.md
@@ -99,7 +99,7 @@ Download the corresponding JDBC driver and place it to the
`catalogs/lakehouse-p
Refer to [Manage Catalogs and
Schemas](./manage-catalogs-and-schemas.md#catalog-operations) for more details.
:::note
-Sensitive catalog properties such as `s3-access-key-id`,
`s3-secret-access-key`, `jdbc-user`, and `jdbc-password` are hidden from the
load catalog response. Use the [credential vending
API](security/credential-vending.md) to retrieve them at runtime.
+Sensitive catalog properties such as `s3-access-key-id`,
`s3-secret-access-key`, `jdbc-user`, and `jdbc-password` are hidden from the
load catalog response. Use the [credential vending
API](security/credential-vending.md) to retrieve them at runtime. Catalog
credential access requires metadata access plus both `USE_SECRETS` and
`INCLUDE_CREDENTIAL_SECRETS`, or metalake ownership.
:::
## Schema
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 2bff4964b5..3986058ebc 100755
--- a/docs/security/access-control.md
+++ b/docs/security/access-control.md
@@ -169,6 +169,8 @@ sets the scope of the grant. Binding a privilege to a type
not listed for it is
|----------------------|-------------------------------------|--------------------------------------------------------------------|
| `CREATE_CATALOG` | Metalake | Create catalogs
|
| `USE_CATALOG` | Metalake, Catalog | Use any catalog
in scope, and reach the objects inside it |
+| `USE_SECRETS` | Metalake, Catalog | Required with
`INCLUDE_CREDENTIAL_SECRETS` for catalog credential access |
+| `INCLUDE_CREDENTIAL_SECRETS` | Metalake, Catalog | Required with
`USE_SECRETS` for catalog credential access |
| `CREATE_SCHEMA` | Metalake, Catalog, Schema | Create schemas
or nested schemas in scope |
| `USE_SCHEMA` | Metalake, Catalog, Schema | Use any schema
in scope, and reach the objects inside it |
| `CREATE_TABLE` | Metalake, Catalog, Schema | Create tables
in any schema in scope |
@@ -258,7 +260,11 @@ ownership, the same as altering it, because the caller
chooses what the server c
Table statistics follow the table itself: reading them takes `SELECT_TABLE` or
`MODIFY_TABLE`,
writing them takes `MODIFY_TABLE`. Model versions follow the model:
`USE_MODEL` to read, owner to
-alter or delete. Fetching a credential takes whatever loading the object takes.
+alter or delete. Catalog credential vending requires metadata access plus both
+`USE_SECRETS` and `INCLUDE_CREDENTIAL_SECRETS`, or metalake ownership. Missing
either
+privilege returns a forbidden error. Catalog ownership alone does not bypass
these checks.
+The two privileges can be granted on a metalake or catalog in the 1.3 branch;
they do not
+introduce a Secrets API. Fileset credential vending retains its path-based
authorization.
The View row applies to metadata operations through both the native Gravitino
REST API and the
Iceberg REST Catalog when authorization is enabled. Listing first requires
access to the schema and
diff --git a/docs/security/credential-vending.md
b/docs/security/credential-vending.md
index ddb4e88d35..c65a41ec45 100644
--- a/docs/security/credential-vending.md
+++ b/docs/security/credential-vending.md
@@ -227,6 +227,29 @@ GET
/api/metalakes/{metalake}/objects/catalog/{catalog}/credentials
The server returns short-lived or static credentials that the client can use
to access the underlying storage directly. These credentials are catalog-level
and are not refreshed. Path-based providers such as `s3-token` and `aws-irsa`
vend nothing at catalog level.
+### Catalog credential access
+
+With authorization enabled, catalog credential vending requires metadata
access plus both
+`USE_SECRETS` and `INCLUDE_CREDENTIAL_SECRETS`, or metalake ownership. These
privileges can
+be granted on a metalake or catalog in the 1.3 branch using the matching
Java/Python client
+or CLI version. `USE_CATALOG` and catalog ownership
+alone do not authorize retrieving the source account. Grant the two privileges
only to
+trusted connectors/operators: catalog credentials carry all source-account
permissions,
+including access beyond individual Gravitino table grants.
+
+Fileset credential authorization remains path-based. Java and Python GVFS on
this branch use
+the fileset credential endpoint directly, without an optional catalog
credential overlay.
+Static fileset credentials can still grant broader source access than the
requested path;
+prefer short-lived scoped credentials when available.
+
+For relational JDBC catalogs, `jdbc-url` must not contain passwords, tokens,
or inline user
+information. Move login credentials to `jdbc-user` and `jdbc-password`
**before upgrading**.
+Legacy credential-bearing URLs are masked on the property read path, including
when
+credential backfill is enabled, but loading a catalog may fail earlier during
configuration
+validation. PostgreSQL catalog ALTER loads the old configuration first, so an
already-upgraded
+deployment must use the previous server version to migrate before upgrading
again.
+JDBC-backed Iceberg/Paimon `uri` properties are outside this URL protection.
+
### Spark and Flink Connector Integration
The Gravitino Spark and Flink connectors automatically call the credential
vending API and inject the returned credentials into the connector's
configuration, so no connector-side credential configuration is needed. For
example, `GravitinoHiveCatalog`, `GravitinoGlueCatalog`,
`GravitinoJdbcCatalog`, and `GravitinoIcebergCatalog` all consume the vended
credentials transparently.
diff --git
a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.java
b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.java
index 7d3c5a4b95..318f264492 100644
---
a/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.java
+++
b/server-common/src/main/java/org/apache/gravitino/server/authorization/expression/AuthorizationExpressionConstants.java
@@ -267,6 +267,21 @@ public class AuthorizationExpressionConstants {
ANY_WRITE_FILESET
""";
+ /** Catalog credential access requires this grant and the
credential-inclusion grant. */
+ public static final String FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION =
+ """
+ METALAKE::OWNER ||
+ ((ANY(USE_SECRETS, METALAKE, CATALOG)) && !(ANY(DENY_USE_SECRETS,
METALAKE, CATALOG)))
+ """;
+
+ /** Catalog credential access requires this grant and the use-secrets grant.
*/
+ public static final String
FILTER_INCLUDE_CREDENTIAL_SECRETS_AUTHORIZATION_EXPRESSION =
+ """
+ METALAKE::OWNER ||
+ ((ANY(INCLUDE_CREDENTIAL_SECRETS, METALAKE, CATALOG))
+ && !(ANY(DENY_INCLUDE_CREDENTIAL_SECRETS, METALAKE, CATALOG)))
+ """;
+
public static final String FILTER_TOPICS_AUTHORIZATION_EXPRESSION =
"""
ANY(OWNER, METALAKE, CATALOG, SCHEMA, TOPIC) ||
diff --git
a/server-common/src/test/java/org/apache/gravitino/server/authorization/expression/TestCatalogCredentialAuthorization.java
b/server-common/src/test/java/org/apache/gravitino/server/authorization/expression/TestCatalogCredentialAuthorization.java
new file mode 100644
index 0000000000..0c65e72e88
--- /dev/null
+++
b/server-common/src/test/java/org/apache/gravitino/server/authorization/expression/TestCatalogCredentialAuthorization.java
@@ -0,0 +1,132 @@
+/*
+ * 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.server.authorization.expression;
+
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.util.Map;
+import java.util.Optional;
+import org.apache.gravitino.Entity;
+import org.apache.gravitino.MetadataObject;
+import org.apache.gravitino.NameIdentifier;
+import org.apache.gravitino.UserPrincipal;
+import org.apache.gravitino.authorization.AuthorizationRequestContext;
+import org.apache.gravitino.authorization.GravitinoAuthorizer;
+import org.apache.gravitino.authorization.Privilege;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.EnumSource;
+
+class TestCatalogCredentialAuthorization {
+ @ParameterizedTest
+ @EnumSource(
+ value = MetadataObject.Type.class,
+ names = {"METALAKE", "CATALOG"})
+ void testGrantsDenialsAndOwnerException(MetadataObject.Type grantScope) {
+ Map<Entity.EntityType, NameIdentifier> names =
+ Map.of(
+ Entity.EntityType.METALAKE, NameIdentifier.of("metalake"),
+ Entity.EntityType.CATALOG, NameIdentifier.of("metalake",
"catalog"));
+ for (boolean owner : new boolean[] {false, true}) {
+ for (boolean use : new boolean[] {false, true}) {
+ for (boolean include : new boolean[] {false, true}) {
+ for (MetadataObject.Type denyScope :
+ new MetadataObject.Type[] {
+ MetadataObject.Type.METALAKE, MetadataObject.Type.CATALOG
+ }) {
+ for (Privilege.Name denied :
+ new Privilege.Name[] {
+ null, Privilege.Name.USE_SECRETS,
Privilege.Name.INCLUDE_CREDENTIAL_SECRETS
+ }) {
+ GravitinoAuthorizer authorizer = mock(GravitinoAuthorizer.class);
+ when(authorizer.isOwner(any(), any(), any(), any()))
+ .thenAnswer(
+ call ->
+ owner
+ && call.<MetadataObject>getArgument(2).type()
+ == MetadataObject.Type.METALAKE);
+ when(authorizer.authorize(any(), any(), any(), any(), any()))
+ .thenAnswer(
+ call -> {
+ if (call.<MetadataObject>getArgument(2).type() !=
grantScope) return false;
+ Privilege.Name privilege = call.getArgument(3);
+ // Metadata access is deliberately insufficient
without both credential
+ // grants.
+ return privilege == Privilege.Name.USE_CATALOG
+ || (privilege == Privilege.Name.USE_SECRETS && use)
+ || (privilege ==
Privilege.Name.INCLUDE_CREDENTIAL_SECRETS && include);
+ });
+ when(authorizer.deny(any(), any(), any(), any(), any()))
+ .thenAnswer(
+ call ->
+ call.<MetadataObject>getArgument(2).type() ==
denyScope
+ && call.<Privilege.Name>getArgument(3) ==
denied);
+ AuthorizationExpressionEvaluator useCheck =
+ new AuthorizationExpressionEvaluator(
+
AuthorizationExpressionConstants.FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION,
+ authorizer);
+ AuthorizationExpressionEvaluator includeCheck =
+ new AuthorizationExpressionEvaluator(
+ AuthorizationExpressionConstants
+
.FILTER_INCLUDE_CREDENTIAL_SECRETS_AUTHORIZATION_EXPRESSION,
+ authorizer);
+ UserPrincipal principal = new UserPrincipal("caller");
+ boolean allowed =
+ useCheck.evaluate(
+ names, new AuthorizationRequestContext(), principal,
Optional.empty())
+ && includeCheck.evaluate(
+ names, new AuthorizationRequestContext(), principal,
Optional.empty());
+ Assertions.assertEquals(owner || (use && include && denied ==
null), allowed);
+ }
+ }
+ }
+ }
+ }
+ }
+
+ @ParameterizedTest
+ @EnumSource(
+ value = MetadataObject.Type.class,
+ names = {"METALAKE", "CATALOG"})
+ void testOnlyMetalakeOwnershipBypassesGrants(MetadataObject.Type ownerScope)
{
+ GravitinoAuthorizer authorizer = mock(GravitinoAuthorizer.class);
+ when(authorizer.isOwner(any(), any(), any(), any()))
+ .thenAnswer(call -> call.<MetadataObject>getArgument(2).type() ==
ownerScope);
+ Map<Entity.EntityType, NameIdentifier> names =
+ Map.of(
+ Entity.EntityType.METALAKE, NameIdentifier.of("metalake"),
+ Entity.EntityType.CATALOG, NameIdentifier.of("metalake",
"catalog"));
+ for (String expression :
+ new String[] {
+
AuthorizationExpressionConstants.FILTER_USE_SECRET_AUTHORIZATION_EXPRESSION,
+ AuthorizationExpressionConstants
+ .FILTER_INCLUDE_CREDENTIAL_SECRETS_AUTHORIZATION_EXPRESSION
+ }) {
+ Assertions.assertEquals(
+ ownerScope == MetadataObject.Type.METALAKE,
+ new AuthorizationExpressionEvaluator(expression, authorizer)
+ .evaluate(
+ names,
+ new AuthorizationRequestContext(),
+ new UserPrincipal("caller"),
+ Optional.empty()));
+ }
+ }
+}
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 ca11fe5e12..7fc6af0540 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
@@ -755,12 +755,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 b597464b1d..4e6f558c2b 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,11 +102,29 @@ 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);
// set the fileset info into the thread local context
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 9f61a1eff5..8aee5ed768 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;
@@ -160,7 +161,10 @@ public abstract class SparkAuthorizationIT extends BaseIT {
Privileges.UseCatalog.allow(),
Privileges.UseSchema.allow(),
Privileges.SelectTable.allow(),
- Privileges.CreateTable.allow()));
+ Privileges.CreateTable.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);
}
@@ -185,6 +189,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 +318,12 @@ public abstract class SparkAuthorizationIT extends BaseIT {
// Create role with CREATE_TABLE but without SELECT_TABLE privilege
SecurableObject catalogObject =
- SecurableObjects.ofCatalog(JDBC_CATALOG,
ImmutableList.of(Privileges.UseCatalog.allow()));
+ SecurableObjects.ofCatalog(
+ JDBC_CATALOG,
+ ImmutableList.of(
+ Privileges.UseCatalog.allow(),
+ Privileges.UseSecrets.allow(),
+ Privileges.IncludeCredentialSecrets.allow()));
SecurableObject schemaObject =
SecurableObjects.ofSchema(
catalogObject,
@@ -335,7 +372,9 @@ public abstract class SparkAuthorizationIT extends BaseIT {
Privileges.UseCatalog.allow(),
Privileges.UseSchema.allow(),
Privileges.SelectTable.allow(),
- Privileges.CreateTable.allow()));
+ Privileges.CreateTable.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 83c1840ce7..af75bf1a41 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
@@ -196,7 +196,10 @@ public abstract class SparkJwksAuthorizationIT extends
BaseIT {
Privileges.UseCatalog.allow(),
Privileges.UseSchema.allow(),
Privileges.CreateTable.allow(),
- Privileges.SelectTable.allow()));
+ Privileges.SelectTable.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);
}
@@ -250,6 +253,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));