You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@gravitino.apache.org by di...@apache.org on 2026/08/25 04:54:53 UTC

(gravitino) branch trino-irc-1.3 created (now 3557943b83)

This is an automated email from the ASF dual-hosted git repository.

diqiu50 pushed a change to branch trino-irc-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git


      at 3557943b83 [Cherry-pick to branch-1.3] fix(trino): share Starburst AI model classes

This branch includes the following new commits:

     new 3484805201 [Cherry-pick to branch-1.3] Feature/trino connector oauth2 user forwarding (#12045)
     new fb42cd6b99 [Cherry-pick to branch-1.3] [#12526] feat(trino-connector): Support Starburst SPI compatibility (#12527)
     new 378829b44b [Cherry-pick to branch-1.3] [#12542] improvement(trino-connector): Support TLS and session role for the internal JDBC connection (#12543)
     new f1beaf7b97 [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Route lakehouse-iceberg catalogs through the Iceberg REST server
     new 13969fdcf9 [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Drop Trino 435-439 support
     new 6214c34693 [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Address review findings on the Iceberg REST routing
     new 66de2d5926 [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Address review findings on the Iceberg REST routing
     new 320489684e [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Discover the Iceberg REST server instead of a manual switch
     new 8e0ac68310 [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Fix IRC discovery port default, worker propagation, and other review findings
     new fcbcfb2ede [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Fix IRC discovery misrouting on static-config-provider and other review findings
     new cef52ce77b [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Address more review findings on the Iceberg REST routing
     new aeec51586d [Cherry-pick to branch-1.3] fix(trino): secure dynamic catalog credentials
     new 3557943b83 [Cherry-pick to branch-1.3] fix(trino): share Starburst AI model classes

The 13 revisions listed above as "new" are entirely new to this
repository and will be described in separate emails.  The revisions
listed as "add" were already present in the repository and have only
been added to this reference.



(gravitino) 06/13: [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Address review findings on the Iceberg REST routing

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diqiu50 pushed a commit to branch trino-irc-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit 6214c3469346115527f9bfea48cbdc4a4e81b8fd
Author: diqiu50 <di...@apache.org>
AuthorDate: Sat Aug 22 21:38:49 2026 +0800

    [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Address review findings on the Iceberg REST routing
    
    Surface the missing rest-uri at connector startup instead of only when a
    catalog load fails inside the refresh loop, where the error is swallowed.
    
    Correct the claim that the REST path is the only one supporting credential
    vending: it is the only one supporting temporary credentials, while static
    keys are still injected on the backend path by applyCredentials.
    
    Derive s3.path-style-access, which S3-compatible stores such as MinIO need,
    and warn when a warehouse scheme has no Trino native file system but the
    catalog vends credentials. Log ignored reserved keys and the ambiguity of
    routing by catalog name alone in multi-metalake mode.
    
    Match Gravitino's case-insensitive handling of catalog-backend, and set the
    Iceberg REST config from an instance initializer so two @BeforeAll methods
    on the same test class no longer race.
    
    (cherry picked from commit a1b67fbd7f56f9522f64f62182696da130beaf93)
---
 docs/trino-connector/catalog-iceberg.md            |  22 ++-
 docs/trino-connector/configuration.md              |   4 +-
 .../docker-script/init/trino/init.sh               |   5 +-
 .../test/container/TrinoITContainers.java          |   4 +
 .../gravitino/integration/test/util/BaseIT.java    |   3 +-
 .../integration/test/TrinoConnectorIT.java         |  24 +--
 .../gravitino/trino/connector/GravitinoConfig.java |  26 ++++
 .../iceberg/IcebergCatalogPropertyConverter.java   | 173 +++++++++++++++------
 .../catalog/iceberg/IcebergConnectorAdapter.java   |  16 +-
 .../trino/connector/TestGravitinoConfig.java       |  12 ++
 .../TestIcebergCatalogPropertyConverter.java       | 163 ++++++++++++++++++-
 11 files changed, 383 insertions(+), 69 deletions(-)

diff --git a/docs/trino-connector/catalog-iceberg.md b/docs/trino-connector/catalog-iceberg.md
index 223b597fe9..dd00d8cab1 100644
--- a/docs/trino-connector/catalog-iceberg.md
+++ b/docs/trino-connector/catalog-iceberg.md
@@ -50,9 +50,20 @@ them, and one catalog could not serve two Trino clusters that reach the IRC by d
 The connector derives everything else from the catalog itself. The Gravitino catalog name is passed
 as both `iceberg.rest-catalog.warehouse` and `iceberg.rest-catalog.prefix` — the Iceberg client
 selects the catalog twice over, first as the query parameter of the `GET /v1/config` call that
-discovers it, then as the path segment of every request after that. The Trino native file system
-(`fs.native-s3.enabled` and `s3.region`, or the GCS and Azure equivalents) is derived from the
-catalog's `warehouse` scheme and storage properties.
+discovers it, then as the path segment of every request after that.
+
+The Trino native file system is derived from the catalog's `warehouse` scheme, because vended
+credentials are only consumed by Trino's native file systems:
+
+| Warehouse scheme                          | Derived properties                                                                                    |
+|:------------------------------------------|:------------------------------------------------------------------------------------------------------|
+| `s3://`, `s3a://`, `s3n://`               | `fs.native-s3.enabled`, plus `s3.region`, `s3.endpoint` and `s3.path-style-access` where the catalog defines `s3-region`, `s3-endpoint` and `s3-path-style-access` |
+| `gs://`                                   | `fs.native-gcs.enabled`                                                                                |
+| `abfs://`, `abfss://`, `wasb://`, `wasbs://` | `fs.native-azure.enabled`                                                                           |
+| anything else (`hdfs://`, `file://`, `oss://`) | none — only `fs.hadoop.enabled`                                                                   |
+
+A scheme in the last row has no Trino native file system, so a catalog that vends credentials for it
+cannot have them applied; the connector logs a warning when it detects that combination.
 
 On the Gravitino side, the IRC must run with the dynamic config provider so it can serve catalogs
 defined in Gravitino:
@@ -81,6 +92,11 @@ gravitino.iceberg.rest-catalog.oauth2.scope=email
 Omitting this block against an authenticated IRC surfaces as an authentication error rather than a
 missing-configuration error, which is easy to misdiagnose.
 
+Four keys are reserved: `iceberg.rest-catalog.uri`, `.warehouse`, `.prefix` and
+`iceberg.catalog.type`. The connector always derives these itself, so setting them through either
+`gravitino.iceberg.rest-catalog.` or a catalog's `trino.bypass.` has no effect — the connector logs
+when it ignores one.
+
 When `gravitino.client.session.forwardUser=true`, the connector also sets
 `iceberg.rest-catalog.session=USER` so that each query carries the end user's identity to the IRC,
 keeping per-user credential vending and per-user authorization intact. Set
diff --git a/docs/trino-connector/configuration.md b/docs/trino-connector/configuration.md
index 1d756be8de..6d225a6cec 100644
--- a/docs/trino-connector/configuration.md
+++ b/docs/trino-connector/configuration.md
@@ -30,8 +30,8 @@ license: "This software is licensed under the Apache License version 2."
 | gravitino.trino.skip-catalog-patterns       | string  | (none)                | The `gravitino.trino.skip-catalog-patterns` defines a comma-separated list of catalog name regex patterns that should be excluded from loading. For example, `test_.*, .*_tmp` excludes all catalogs starting with `test_` or ending with `_tmp`.                                                                                                | No       |
 | gravitino.use-single-metalake               | boolean | true                  | If `true`, only one metalake is used and catalogs are identified by `<catalog_name>`. If `false`, multi-metalake mode is enabled and catalogs are identified by `<metalake_name>.<catalog_name>`.                                                                                                                                                | No       |
 | gravitino.iceberg.rest-enabled              | boolean | true                  | If `true`, `lakehouse-iceberg` catalogs are loaded through the Gravitino Iceberg REST server (IRC) instead of being translated into Trino's `jdbc` or `hive_metastore` Iceberg catalog type. This is what makes credential vending work. Requires `gravitino.iceberg.rest-uri`. Set to `false` for a deployment that does not run the IRC.                                    | No       |
-| gravitino.iceberg.rest-uri                  | string  | (none)                | The endpoint of the Gravitino Iceberg REST server, for example `http://gravitino-host:9001/iceberg`. Required when `gravitino.iceberg.rest-enabled` is `true` and the metalake contains `lakehouse-iceberg` catalogs.                                                                                               | No       |
-| gravitino.iceberg.rest-catalog.             | string  | (none)                | The configuration key prefix for properties passed through to the internal Trino Iceberg REST catalog. The prefix is rewritten to `iceberg.rest-catalog.`, so `gravitino.iceberg.rest-catalog.security=OAUTH2` becomes `iceberg.rest-catalog.security=OAUTH2`.                                                      | No       |
+| gravitino.iceberg.rest-uri                  | string  | (none)                | The endpoint of the Gravitino Iceberg REST server, for example `http://gravitino-host:9001/iceberg`. Required when `gravitino.iceberg.rest-enabled` is `true` and the metalake contains `lakehouse-iceberg` catalogs whose `catalog-backend` is not `rest`.                                                          | No       |
+| gravitino.iceberg.rest-catalog.             | string  | (none)                | The configuration key prefix for properties passed through to the internal Trino Iceberg REST catalog. The prefix is rewritten to `iceberg.rest-catalog.`, so `gravitino.iceberg.rest-catalog.security=OAUTH2` becomes `iceberg.rest-catalog.security=OAUTH2`. The `uri`, `warehouse` and `prefix` keys are reserved and always derived by the connector.                     | No       |
 
 To configure the Gravitino client, use properties prefixed with `gravitino.client.`. These properties will directly passed to the Gravitino client.
 
diff --git a/integration-test-common/docker-script/init/trino/init.sh b/integration-test-common/docker-script/init/trino/init.sh
index d713708e52..a65ec5ab90 100644
--- a/integration-test-common/docker-script/init/trino/init.sh
+++ b/integration-test-common/docker-script/init/trino/init.sh
@@ -34,8 +34,9 @@ cp /usr/lib/trino/plugin/mysql/*mysql-connector-j-*.jar /usr/lib/trino/plugin/ic
 sed -i "s/GRAVITINO_HOST_IP:GRAVITINO_HOST_PORT/${GRAVITINO_HOST_IP}:${GRAVITINO_HOST_PORT}/g" /etc/trino/catalog/gravitino.properties
 # Update `gravitino.metalake = GRAVITINO_METALAKE_NAME` in the `conf/catalog/gravitino.properties`
 sed -i "s/GRAVITINO_METALAKE_NAME/${GRAVITINO_METALAKE_NAME}/g" /etc/trino/catalog/gravitino.properties
-# Update `gravitino.iceberg.rest-uri` in the `conf/catalog/gravitino.properties`. It uses its own
-# placeholders so that the substitution above cannot leave a half-replaced host behind.
+# Update `gravitino.iceberg.rest-uri` in the `conf/catalog/gravitino.properties`. The Iceberg REST
+# server runs on the same host as the Gravitino server but on a different port, so it needs its own
+# placeholder pair — reusing GRAVITINO_HOST_IP:GRAVITINO_HOST_PORT would substitute the server port.
 sed -i "s/GRAVITINO_ICEBERG_REST_HOST:GRAVITINO_ICEBERG_REST_PORT/${GRAVITINO_HOST_IP}:${GRAVITINO_ICEBERG_REST_PORT}/g" /etc/trino/catalog/gravitino.properties
 # Update `node.id=NODE_ID` in the `/conf/node.properties`
 sed -i "s/NODE_ID/${RANDOM}-${RANDOM}-${RANDOM}-${RANDOM}-${RANDOM}/g" /etc/trino/node.properties
diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/TrinoITContainers.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/TrinoITContainers.java
index 14fe768c0b..572b948d55 100644
--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/TrinoITContainers.java
+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/TrinoITContainers.java
@@ -84,6 +84,10 @@ public class TrinoITContainers implements AutoCloseable {
     env.put("HIVE_RUNTIME_VERSION", hiveRuntimeVersion);
     if (icebergRestServerPort > 0) {
       env.put("GRAVITINO_ICEBERG_REST_PORT", String.valueOf(icebergRestServerPort));
+    } else {
+      LOG.info(
+          "No Iceberg REST server port supplied; Trino falls back to the compose default. "
+              + "Catalogs routed through the Iceberg REST server will not work in this container.");
     }
     env.put("TRINO_CONNECTOR_TEST", String.valueOf(isTrinoConnectorTest));
     if (System.getProperty("gravitino.log.path") != null) {
diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java
index f3a0724ef0..0c247a22f1 100644
--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java
+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java
@@ -688,7 +688,8 @@ public class BaseIT {
   }
 
   /**
-   * Returns the port the Iceberg REST auxiliary service listens on.
+   * Returns the port the Iceberg REST auxiliary service listens on. Only valid once {@link
+   * #startIntegrationTest()} has run, since it reads the started server's config.
    *
    * @return the Iceberg REST service port
    */
diff --git a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java
index d0796e044f..1be5ef43bc 100644
--- a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java
+++ b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java
@@ -23,7 +23,6 @@ import static org.testcontainers.shaded.org.awaitility.Awaitility.await;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
-import java.net.URI;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -94,18 +93,19 @@ public class TrinoConnectorIT extends BaseIT {
   private static GravitinoMetalake metalake;
   private static Catalog catalog;
 
-  @BeforeAll
-  @Override
-  public void startIntegrationTest() throws Exception {
+  // Set from an instance initializer rather than an overridden @BeforeAll: BaseIT is PER_CLASS, so
+  // the instance exists before any lifecycle method runs, and JUnit only guarantees that a
+  // superclass @BeforeAll precedes a subclass one — two @BeforeAll methods declared on this same
+  // class would have no defined order relative to each other.
+  {
     // The Trino connector loads every lakehouse-iceberg catalog through the Iceberg REST server,
     // so the auxiliary service has to run and serve this test's metalake.
-    ignoreIcebergAuxRestService = false;
-    customConfigs.put(
-        GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.ICEBERG_REST_CATALOG_CONFIG_PROVIDER,
-        IcebergConstants.DYNAMIC_ICEBERG_CATALOG_CONFIG_PROVIDER_NAME);
-    customConfigs.put(
-        GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_METALAKE, metalakeName);
-    super.startIntegrationTest();
+    enableIcebergAuxRestService(
+        ImmutableMap.of(
+            GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.ICEBERG_REST_CATALOG_CONFIG_PROVIDER,
+            IcebergConstants.DYNAMIC_ICEBERG_CATALOG_CONFIG_PROVIDER_NAME,
+            GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_METALAKE,
+            metalakeName));
   }
 
   @BeforeAll
@@ -131,7 +131,7 @@ public class TrinoConnectorIT extends BaseIT {
         trinoConfDir,
         System.getenv("GRAVITINO_ROOT_DIR") + "/trino-connector/build/libs",
         getGravitinoServerPort(),
-        URI.create(getIcebergRestServiceUri()).getPort(),
+        getIcebergRestServicePort(),
         metalakeName);
     Assertions.assertTrue(
         containerSuite.getTrinoContainer().checkSyncCatalogFromGravitino(5, catalogName),
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
index b6a518584a..50af268066 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
@@ -35,10 +35,14 @@ import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.gravitino.trino.connector.security.GravitinoAuthProvider;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /** Gravitino config. */
 public class GravitinoConfig {
 
+  private static final Logger LOG = LoggerFactory.getLogger(GravitinoConfig.class);
+
   // Trino config keys
   /** The Trino discovery URI. */
   private static final String TRINO_DISCOVERY_URI = "discovery.uri";
@@ -321,6 +325,28 @@ public class GravitinoConfig {
           "Config `gravitino.trino.skip-catalog-patterns` is invalid because it contains an illegal regular expression",
           e);
     }
+    warnOnMissingIcebergRestUri();
+  }
+
+  /**
+   * Warns at startup when the Iceberg REST routing is on but has no endpoint. Without this, the
+   * failure only surfaces once a lakehouse-iceberg catalog is loaded, and that error is swallowed
+   * by the catalog refresh loop, leaving the user with an unexplained missing catalog.
+   */
+  private void warnOnMissingIcebergRestUri() {
+    // Only the statically configured connector warns; the dynamic per-catalog ones would repeat it.
+    if (isDynamicConnector()
+        || !isIcebergRestEnabled()
+        || StringUtils.isNotBlank(getIcebergRestUri())) {
+      return;
+    }
+    LOG.warn(
+        "'{}' is enabled but '{}' is not set, so every lakehouse-iceberg catalog will fail to "
+            + "load. Set the Iceberg REST server endpoint, or set '{}=false' to load Iceberg "
+            + "catalogs through their catalog backend instead.",
+        GRAVITINO_ICEBERG_REST_ENABLED.key,
+        GRAVITINO_ICEBERG_REST_URI.key,
+        GRAVITINO_ICEBERG_REST_ENABLED.key);
   }
 
   /**
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
index 8073f1e1c2..dd8a492e1d 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
@@ -22,6 +22,7 @@ package org.apache.gravitino.trino.connector.catalog.iceberg;
 import com.google.common.collect.Sets;
 import io.trino.spi.TrinoException;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 import java.util.Set;
@@ -30,6 +31,7 @@ import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
 import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergPropertiesUtils;
 import org.apache.gravitino.credential.AzureAccountKeyCredential;
 import org.apache.gravitino.credential.Credential;
+import org.apache.gravitino.credential.CredentialConstants;
 import org.apache.gravitino.credential.JdbcCredential;
 import org.apache.gravitino.credential.S3SecretKeyCredential;
 import org.apache.gravitino.storage.S3Properties;
@@ -37,6 +39,8 @@ import org.apache.gravitino.trino.connector.GravitinoConfig;
 import org.apache.gravitino.trino.connector.GravitinoErrorCode;
 import org.apache.gravitino.trino.connector.catalog.CatalogPropertyConverter;
 import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * A property converter for Iceberg catalogs that handles the conversion between Trino and Gravitino
@@ -45,6 +49,8 @@ import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
  */
 public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
 
+  private static final Logger LOG = LoggerFactory.getLogger(IcebergCatalogPropertyConverter.class);
+
   private static final Set<String> JDBC_BACKEND_REQUIRED_PROPERTIES = Set.of("jdbc-driver", "uri");
 
   private static final Set<String> HIVE_BACKEND_REQUIRED_PROPERTIES = Set.of("uri");
@@ -65,6 +71,15 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
   private static final String TRINO_FS_NATIVE_AZURE_ENABLED = "fs.native-azure.enabled";
   private static final String TRINO_S3_REGION = "s3.region";
   private static final String TRINO_S3_ENDPOINT = "s3.endpoint";
+  private static final String TRINO_S3_PATH_STYLE_ACCESS = "s3.path-style-access";
+
+  /** Routing keys the connector always derives itself; they cannot be overridden. */
+  private static final List<String> RESERVED_REST_PROPERTIES =
+      List.of(
+          TRINO_ICEBERG_CATALOG_TYPE,
+          TRINO_ICEBERG_REST_URI,
+          TRINO_ICEBERG_REST_WAREHOUSE,
+          TRINO_ICEBERG_REST_PREFIX);
 
   /**
    * Injects credentials from credential vending into the Iceberg catalog config. Applies JDBC
@@ -100,7 +115,9 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
       throw new TrinoException(
           GravitinoErrorCode.GRAVITINO_MISSING_REQUIRED_PROPERTY,
           "Missing required property 'catalog-backend'");
-    switch (backend) {
+    // Gravitino accepts the backend as an enum value, and its own consumers upper-case it before
+    // resolving, so the value reaching here may be in any case.
+    switch (backend.toLowerCase(Locale.ROOT)) {
       case "hive":
         stringStringMap = buildHiveBackendProperties(properties);
         break;
@@ -121,6 +138,73 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
     return config;
   }
 
+  /**
+   * Builds the Trino Iceberg connector config that reaches this catalog through the Gravitino
+   * Iceberg REST server, regardless of the catalog backend Gravitino uses to store its metadata.
+   *
+   * <p>This is the only path on which <em>temporary</em> credentials work — {@code s3-token} and
+   * its GCS and ADLS counterparts. The Iceberg REST protocol issues a fresh one per table access,
+   * while Trino's jdbc and hive_metastore Iceberg catalog types have nowhere to put the session
+   * token of an STS credential. Static-key credentials are unaffected: they are still injected on
+   * the backend path by {@link #applyCredentials}.
+   *
+   * @param catalog the Gravitino catalog to load
+   * @param gravitinoConfig the connector configuration holding the Iceberg REST server endpoint
+   * @return the Trino Iceberg connector config
+   * @throws TrinoException if {@code gravitino.iceberg.rest-uri} is not configured
+   */
+  public Map<String, String> buildIcebergRestProperties(
+      GravitinoCatalog catalog, GravitinoConfig gravitinoConfig) {
+    String restUri = gravitinoConfig.getIcebergRestUri();
+    if (StringUtils.isBlank(restUri)) {
+      throw new TrinoException(
+          GravitinoErrorCode.GRAVITINO_MISSING_CONFIG,
+          "Missing required config 'gravitino.iceberg.rest-uri'. Set it to the Gravitino Iceberg "
+              + "REST server endpoint, for example http://localhost:9001/iceberg, or set "
+              + "'gravitino.iceberg.rest-enabled=false' to load Iceberg catalogs through their "
+              + "catalog backend instead.");
+    }
+
+    Map<String, String> config = new HashMap<>();
+    // The order of put operations determines the priority of parameters.
+    config.putAll(buildStorageProperties(catalog.getProperties()));
+    config.put(TRINO_ICEBERG_REST_VENDED_CREDENTIALS, "true");
+    if (gravitinoConfig.isForwardUser()) {
+      config.put(TRINO_ICEBERG_REST_SESSION, "USER");
+    }
+    // The catalog's own trino.bypass properties override the defaults above, so that a Trino
+    // release renaming one of them can be worked around without a connector change.
+    config.putAll(super.gravitinoToEngineProperties(catalog.getProperties()));
+    // The IRC's own authentication is a cluster-level operational setting, so it takes precedence
+    // over anything set on a single catalog.
+    config.putAll(gravitinoConfig.getIcebergRestCatalogConfig());
+
+    warnOnReservedOverrides(catalog, config);
+
+    config.put(TRINO_ICEBERG_CATALOG_TYPE, TRINO_ICEBERG_CATALOG_TYPE_REST);
+    config.put(TRINO_ICEBERG_REST_URI, restUri);
+    // The Iceberg client selects the catalog twice over: `warehouse` is the query parameter of the
+    // initial GET /v1/config that discovers the catalog, and `prefix` is the path segment of every
+    // request after it. Setting only the latter leaves the config call without a catalog name.
+    // The server echoes `prefix` back as a config default, so setting it here is belt-and-braces.
+    config.put(TRINO_ICEBERG_REST_WAREHOUSE, catalog.getName());
+    config.put(TRINO_ICEBERG_REST_PREFIX, catalog.getName());
+
+    if (!gravitinoConfig.singleMetalakeMode()) {
+      // The IRC serves exactly one metalake, and the prefix carries only the catalog name, so two
+      // metalakes holding a same-named catalog both resolve to whichever one the IRC was started
+      // with.
+      LOG.warn(
+          "Catalog '{}' in metalake '{}' is routed to the Iceberg REST server using the catalog "
+              + "name alone. In multi-metalake mode this is ambiguous: the Iceberg REST server "
+              + "serves a single metalake, so a same-named catalog in another metalake resolves to "
+              + "the same prefix.",
+          catalog.getName(),
+          catalog.getMetalake());
+    }
+    return config;
+  }
+
   private Map<String, String> buildHiveBackendProperties(Map<String, String> properties) {
     Set<String> missingProperty =
         Sets.difference(HIVE_BACKEND_REQUIRED_PROPERTIES, properties.keySet());
@@ -167,51 +251,16 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
     return jdbcProperties;
   }
 
-  /**
-   * Builds the Trino Iceberg connector config that reaches this catalog through the Gravitino
-   * Iceberg REST server, regardless of the catalog backend Gravitino uses to store its metadata.
-   *
-   * <p>This is the only path on which credential vending works: the Iceberg REST protocol issues a
-   * fresh temporary credential per table access, while Trino's jdbc and hive_metastore Iceberg
-   * catalog types have nowhere to put the session token of an STS credential.
-   *
-   * @param catalog the Gravitino catalog to load
-   * @param gravitinoConfig the connector configuration holding the Iceberg REST server endpoint
-   * @return the Trino Iceberg connector config
-   */
-  public Map<String, String> buildIcebergRestProperties(
-      GravitinoCatalog catalog, GravitinoConfig gravitinoConfig) {
-    String restUri = gravitinoConfig.getIcebergRestUri();
-    if (StringUtils.isBlank(restUri)) {
-      throw new TrinoException(
-          GravitinoErrorCode.GRAVITINO_MISSING_CONFIG,
-          "Missing required config 'gravitino.iceberg.rest-uri'. Set it to the Gravitino Iceberg "
-              + "REST server endpoint, for example http://localhost:9001/iceberg, or set "
-              + "'gravitino.iceberg.rest-enabled=false' to load Iceberg catalogs through their "
-              + "catalog backend instead.");
-    }
-
-    Map<String, String> config = new HashMap<>();
-    // The order of put operations determines the priority of parameters.
-    config.putAll(buildStorageProperties(catalog.getProperties()));
-    config.put(TRINO_ICEBERG_REST_VENDED_CREDENTIALS, "true");
-    if (gravitinoConfig.isForwardUser()) {
-      config.put(TRINO_ICEBERG_REST_SESSION, "USER");
+  private void warnOnReservedOverrides(GravitinoCatalog catalog, Map<String, String> config) {
+    for (String reserved : RESERVED_REST_PROPERTIES) {
+      if (config.containsKey(reserved)) {
+        LOG.info(
+            "Property '{}' set on catalog '{}' is ignored; the connector always derives it when "
+                + "routing through the Iceberg REST server.",
+            reserved,
+            catalog.getName());
+      }
     }
-    // The catalog's own trino.bypass properties override the defaults above, so that a Trino
-    // release renaming one of them can be worked around without a connector change.
-    config.putAll(super.gravitinoToEngineProperties(catalog.getProperties()));
-    // The Iceberg REST server endpoint and its authentication are cluster-level operational
-    // settings, so they take precedence over anything set on a single catalog.
-    config.putAll(gravitinoConfig.getIcebergRestCatalogConfig());
-    config.put(TRINO_ICEBERG_CATALOG_TYPE, TRINO_ICEBERG_CATALOG_TYPE_REST);
-    config.put(TRINO_ICEBERG_REST_URI, restUri);
-    // The Iceberg client selects the catalog twice over: `warehouse` is the query parameter of the
-    // initial GET /v1/config that discovers the catalog, and `prefix` is the path segment of every
-    // request after it. Setting only the latter leaves the config call without a catalog name.
-    config.put(TRINO_ICEBERG_REST_WAREHOUSE, catalog.getName());
-    config.put(TRINO_ICEBERG_REST_PREFIX, catalog.getName());
-    return config;
   }
 
   /**
@@ -221,6 +270,8 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
    */
   private Map<String, String> buildStorageProperties(Map<String, String> properties) {
     Map<String, String> storageProperties = new HashMap<>();
+    // Always available as the fallback; where a native file system is also enabled below, that one
+    // takes precedence for its own scheme.
     storageProperties.put(TRINO_FS_HADOOP_ENABLED, "true");
 
     String warehouse = properties.get(IcebergConstants.WAREHOUSE);
@@ -238,6 +289,12 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
             properties, S3Properties.GRAVITINO_S3_REGION, storageProperties, TRINO_S3_REGION);
         copyProperty(
             properties, S3Properties.GRAVITINO_S3_ENDPOINT, storageProperties, TRINO_S3_ENDPOINT);
+        // Required by S3-compatible stores such as MinIO and Ceph, which a custom endpoint implies.
+        copyProperty(
+            properties,
+            S3Properties.GRAVITINO_S3_PATH_STYLE_ACCESS,
+            storageProperties,
+            TRINO_S3_PATH_STYLE_ACCESS);
         break;
       case "gs":
         storageProperties.put(TRINO_FS_NATIVE_GCS_ENABLED, "true");
@@ -249,12 +306,36 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
         storageProperties.put(TRINO_FS_NATIVE_AZURE_ENABLED, "true");
         break;
       default:
-        // hdfs, file and any scheme without a Trino native file system stay on fs.hadoop.enabled.
+        warnOnSchemeWithoutNativeFileSystem(properties, warehouse, scheme);
         break;
     }
     return storageProperties;
   }
 
+  /**
+   * Warns when a warehouse scheme has no Trino native file system but the catalog vends
+   * credentials. The Hadoop file system cannot consume a vended credential, so table access would
+   * fail at read time with a storage authentication error far from its cause.
+   */
+  private void warnOnSchemeWithoutNativeFileSystem(
+      Map<String, String> properties, String warehouse, String scheme) {
+    // hdfs and file legitimately run on the Hadoop file system, and a warehouse without a scheme
+    // is a plain path. None of them vend credentials.
+    if (!warehouse.contains("://") || "hdfs".equals(scheme) || "file".equals(scheme)) {
+      return;
+    }
+    if (StringUtils.isBlank(properties.get(CredentialConstants.CREDENTIAL_PROVIDERS))) {
+      return;
+    }
+    LOG.warn(
+        "Warehouse scheme '{}' has no Trino native file system, so the credentials vended by "
+            + "'{}' cannot be applied. Table access falls back to the Hadoop file system and may "
+            + "fail to authenticate. Schemes with a native file system: s3/s3a/s3n, gs, "
+            + "abfs/abfss/wasb/wasbs.",
+        scheme,
+        properties.get(CredentialConstants.CREDENTIAL_PROVIDERS));
+  }
+
   private void copyProperty(
       Map<String, String> source, String sourceKey, Map<String, String> target, String targetKey) {
     String value = source.get(sourceKey);
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java
index 102c15d0f5..1480dc13d4 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java
@@ -30,6 +30,8 @@ import org.apache.gravitino.trino.connector.GravitinoConfig;
 import org.apache.gravitino.trino.connector.catalog.CatalogConnectorAdapter;
 import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadataAdapter;
 import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Transforming Apache Iceberg connector configuration and components into Apache Gravitino
@@ -37,6 +39,8 @@ import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
  */
 public class IcebergConnectorAdapter implements CatalogConnectorAdapter {
 
+  private static final Logger LOG = LoggerFactory.getLogger(IcebergConnectorAdapter.class);
+
   private static final String CONNECTOR_ICEBERG = "iceberg";
   private static final String REST_CATALOG_BACKEND = "rest";
 
@@ -61,11 +65,19 @@ public class IcebergConnectorAdapter implements CatalogConnectorAdapter {
       GravitinoCatalog catalog, Credential[] credentials) throws Exception {
     // The catalog backend describes how Gravitino stores the metadata; it does not decide how
     // Trino reaches the data. Unless the routing is disabled, every catalog is loaded through the
-    // Gravitino Iceberg REST server, which is the only path that supports credential vending.
+    // Gravitino Iceberg REST server, the only path that supports temporary credentials.
     // A catalog that already has a REST backend keeps pointing at its own configured endpoint.
     if (config.isIcebergRestEnabled()
-        && !REST_CATALOG_BACKEND.equals(
+        && !REST_CATALOG_BACKEND.equalsIgnoreCase(
             catalog.getProperty(IcebergConstants.CATALOG_BACKEND, null))) {
+      // `credentials` is intentionally unused here: with vended credentials enabled, Trino obtains
+      // a fresh one per table access over the REST protocol, rather than the catalog-level
+      // snapshot applyCredentials installs.
+      LOG.debug(
+          "Routing catalog '{}' through the Iceberg REST server; its {} catalog-level credential(s)"
+              + " are not applied because the REST protocol vends one per table access.",
+          catalog.getName(),
+          credentials.length);
       return catalogConverter.buildIcebergRestProperties(catalog, config);
     }
 
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
index c31c594be0..357280cf90 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
@@ -353,6 +353,18 @@ public class TestGravitinoConfig {
     assertTrue(catalogConfig.contains("\"gravitino.iceberg.rest-catalog.security\"='OAUTH2'"));
   }
 
+  @Test
+  public void testToCatalogConfigPropagatesIcebergRestEnabled() {
+    // The switch rides the exact-key loop rather than the prefix filter; if it fails to propagate,
+    // the coordinator and the workers build different configs for the same catalog.
+    GravitinoConfig config =
+        new GravitinoConfig(
+            ImmutableMap.of(
+                "gravitino.metalake", "user_001", "gravitino.iceberg.rest-enabled", "false"));
+
+    assertTrue(config.toCatalogConfig().contains("\"gravitino.iceberg.rest-enabled\"='false'"));
+  }
+
   private static boolean skipCatalog(String catalogName, GravitinoConfig config) {
     for (Pattern pattern : config.getSkipCatalogPatterns()) {
       if (pattern.matcher(catalogName).matches()) {
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
index fc3571c8e8..f09e4d7469 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
@@ -27,6 +27,7 @@ import org.apache.gravitino.Catalog;
 import org.apache.gravitino.catalog.property.PropertyConverter;
 import org.apache.gravitino.credential.Credential;
 import org.apache.gravitino.credential.JdbcCredential;
+import org.apache.gravitino.credential.S3SecretKeyCredential;
 import org.apache.gravitino.trino.connector.GravitinoConfig;
 import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
 import org.apache.gravitino.trino.connector.metadata.TestGravitinoCatalog;
@@ -451,11 +452,171 @@ public class TestIcebergCatalogPropertyConverter {
   private static Map<String, String> buildConnectorConfig(
       String catalogName, Map<String, String> properties, GravitinoConfig gravitinoConfig)
       throws Exception {
+    return buildConnectorConfig(catalogName, properties, gravitinoConfig, new Credential[0]);
+  }
+
+  @Test
+  public void testIcebergRestPathIgnoresCatalogLevelCredentials() throws Exception {
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .put("catalog-backend", "jdbc")
+            .put("uri", "jdbc:postgresql://localhost:5432/iceberg")
+            .put("jdbc-driver", "org.postgresql.Driver")
+            .put("warehouse", "s3://bucket/warehouse/")
+            .build();
+    Credential[] credentials = {
+      new JdbcCredential("root", "ds123"), new S3SecretKeyCredential("AKIAEXAMPLE", "secret")
+    };
+
+    Map<String, String> config =
+        buildConnectorConfig(
+            "catalog1", properties, icebergRestEnabledConfig(ImmutableMap.of()), credentials);
+
+    // The REST protocol vends a fresh credential per table access, so the catalog-level snapshot
+    // must not be pinned into the connector config.
+    Assertions.assertNull(config.get("iceberg.jdbc-catalog.connection-user"));
+    Assertions.assertNull(config.get("iceberg.jdbc-catalog.connection-password"));
+    Assertions.assertNull(config.get("hive.s3.aws-access-key"));
+    Assertions.assertNull(config.get("hive.s3.aws-secret-key"));
+    Assertions.assertEquals("true", config.get("iceberg.rest-catalog.vended-credentials-enabled"));
+
+    // The backend path still applies them.
+    Map<String, String> legacyConfig =
+        buildConnectorConfig("catalog1", properties, icebergRestDisabledConfig(), credentials);
+    Assertions.assertEquals("root", legacyConfig.get("iceberg.jdbc-catalog.connection-user"));
+    Assertions.assertEquals("AKIAEXAMPLE", legacyConfig.get("hive.s3.aws-access-key"));
+  }
+
+  @Test
+  public void testIcebergRestReservedPropertiesResistCatalogOverride() throws Exception {
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .put("catalog-backend", "jdbc")
+            .put("warehouse", "s3://bucket/warehouse/")
+            .put("trino.bypass.iceberg.catalog.type", "jdbc")
+            .put("trino.bypass.iceberg.rest-catalog.uri", "http://elsewhere:9001/iceberg")
+            .put("trino.bypass.iceberg.rest-catalog.prefix", "other_catalog")
+            .put("trino.bypass.iceberg.rest-catalog.warehouse", "other_catalog")
+            .build();
+
+    Map<String, String> config =
+        buildConnectorConfig("catalog1", properties, icebergRestEnabledConfig(ImmutableMap.of()));
+
+    // A catalog property must never redirect the connector at another endpoint or catalog.
+    Assertions.assertEquals("rest", config.get("iceberg.catalog.type"));
+    Assertions.assertEquals(
+        "http://localhost:9001/iceberg", config.get("iceberg.rest-catalog.uri"));
+    Assertions.assertEquals("catalog1", config.get("iceberg.rest-catalog.prefix"));
+    Assertions.assertEquals("catalog1", config.get("iceberg.rest-catalog.warehouse"));
+  }
+
+  @Test
+  public void testConnectorRestCatalogConfigOverridesCatalogBypass() throws Exception {
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .put("catalog-backend", "jdbc")
+            .put("warehouse", "s3://bucket/warehouse/")
+            .put("trino.bypass.iceberg.rest-catalog.security", "NONE")
+            .build();
+
+    Map<String, String> config =
+        buildConnectorConfig(
+            "catalog1",
+            properties,
+            icebergRestEnabledConfig(
+                ImmutableMap.of("gravitino.iceberg.rest-catalog.security", "OAUTH2")));
+
+    // Cluster-level operational settings outrank per-catalog properties.
+    Assertions.assertEquals("OAUTH2", config.get("iceberg.rest-catalog.security"));
+  }
+
+  @Test
+  public void testBuildConnectorPropertiesStorageDetectionEdgeCases() throws Exception {
+    // s3a/s3n aliases and an uppercase scheme all resolve to the native S3 file system.
+    for (String warehouse : new String[] {"s3a://bucket/wh", "s3n://bucket/wh", "S3://bucket/wh"}) {
+      Map<String, String> config =
+          buildConnectorConfig(
+              "catalog1",
+              ImmutableMap.of("catalog-backend", "jdbc", "warehouse", warehouse),
+              icebergRestEnabledConfig(ImmutableMap.of()));
+      Assertions.assertEquals(
+          "true", config.get("fs.native-s3.enabled"), "warehouse: " + warehouse);
+    }
+
+    // A warehouse without a scheme is a plain path and stays on the Hadoop file system.
+    Map<String, String> schemeless =
+        buildConnectorConfig(
+            "catalog1",
+            ImmutableMap.of("catalog-backend", "jdbc", "warehouse", "gt_iceberg_rest"),
+            icebergRestEnabledConfig(ImmutableMap.of()));
+    Assertions.assertEquals("true", schemeless.get("fs.hadoop.enabled"));
+    Assertions.assertNull(schemeless.get("fs.native-s3.enabled"));
+
+    // No warehouse at all.
+    Map<String, String> noWarehouse =
+        buildConnectorConfig(
+            "catalog1",
+            ImmutableMap.of("catalog-backend", "jdbc"),
+            icebergRestEnabledConfig(ImmutableMap.of()));
+    Assertions.assertEquals("true", noWarehouse.get("fs.hadoop.enabled"));
+    Assertions.assertNull(noWarehouse.get("fs.native-s3.enabled"));
+    Assertions.assertNull(noWarehouse.get("fs.native-gcs.enabled"));
+    Assertions.assertNull(noWarehouse.get("fs.native-azure.enabled"));
+
+    // oss:// has no Trino native file system, so nothing is enabled beyond Hadoop.
+    Map<String, String> oss =
+        buildConnectorConfig(
+            "catalog1",
+            ImmutableMap.of(
+                "catalog-backend", "jdbc",
+                "warehouse", "oss://bucket/wh",
+                "credential-providers", "oss-token"),
+            icebergRestEnabledConfig(ImmutableMap.of()));
+    Assertions.assertEquals("true", oss.get("fs.hadoop.enabled"));
+    Assertions.assertNull(oss.get("fs.native-s3.enabled"));
+  }
+
+  @Test
+  public void testBuildConnectorPropertiesCopiesS3PathStyleAccess() throws Exception {
+    Map<String, String> config =
+        buildConnectorConfig(
+            "catalog1",
+            ImmutableMap.of(
+                "catalog-backend", "jdbc",
+                "warehouse", "s3://bucket/wh",
+                "s3-endpoint", "http://minio:9000",
+                "s3-path-style-access", "true"),
+            icebergRestEnabledConfig(ImmutableMap.of()));
+
+    // S3-compatible stores such as MinIO need path-style addressing to resolve the bucket.
+    Assertions.assertEquals("true", config.get("s3.path-style-access"));
+    Assertions.assertEquals("http://minio:9000", config.get("s3.endpoint"));
+  }
+
+  @Test
+  public void testRestBackendIsNotReRoutedRegardlessOfCase() throws Exception {
+    Map<String, String> config =
+        buildConnectorConfig(
+            "catalog1",
+            ImmutableMap.of("catalog-backend", "REST", "uri", "http://other-irc:9001/iceberg"),
+            icebergRestEnabledConfig(ImmutableMap.of()));
+
+    Assertions.assertEquals(
+        "http://other-irc:9001/iceberg", config.get("iceberg.rest-catalog.uri"));
+    Assertions.assertNull(config.get("iceberg.rest-catalog.prefix"));
+  }
+
+  private static Map<String, String> buildConnectorConfig(
+      String catalogName,
+      Map<String, String> properties,
+      GravitinoConfig gravitinoConfig,
+      Credential[] credentials)
+      throws Exception {
     Catalog mockCatalog =
         TestGravitinoCatalog.mockCatalog(
             catalogName, "lakehouse-iceberg", "test catalog", Catalog.Type.RELATIONAL, properties);
     return new IcebergConnectorAdapter(gravitinoConfig)
-        .buildInternalConnectorConfig(new GravitinoCatalog("test", mockCatalog), new Credential[0]);
+        .buildInternalConnectorConfig(new GravitinoCatalog("test", mockCatalog), credentials);
   }
 
   private static GravitinoConfig icebergRestDisabledConfig() {


(gravitino) 10/13: [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Fix IRC discovery misrouting on static-config-provider and other review findings

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diqiu50 pushed a commit to branch trino-irc-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit fcbcfb2ede24512d6aad6e4093cbfce02cba93a7
Author: diqiu50 <di...@apache.org>
AuthorDate: Mon Aug 24 20:44:41 2026 +0800

    [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Fix IRC discovery misrouting on static-config-provider and other review findings
    
    - Only report the Iceberg REST server's endpoint when it runs the dynamic
      config provider; the default static provider serves catalogs unrelated
      to Gravitino catalog names, so reporting it there would misroute every
      Iceberg catalog after upgrade.
    - Log discovery failures at WARN on state transitions instead of always
      at DEBUG, so a persistent failure is visible without spamming logs for
      the expected old-server case.
    - Honor the deprecated gravitino.auxService.iceberg-rest.* config form
      when resolving the reported host/port, matching what the Iceberg REST
      server itself sees.
    - Redact credential/token/secret/password-looking properties before
      logging the CREATE CATALOG statement.
    - Add log lines for the previously-silent provider/metalake-mismatch
      null-return paths.
    - Add test coverage for CatalogConnectorManager's discovery polling and
      CatalogRegister's embed-then-serialize wiring, plus a couple of gaps
      around manual-vs-discovered precedence and the non-Iceberg guard.
    
    (cherry picked from commit b22c372e821359002f009d0fb280274893161f5f)
---
 .../auxiliary/AuxiliaryServiceManager.java         | 18 +++++
 .../auxiliary/TestAuxiliaryServiceManager.java     | 39 +++++++++
 .../web/rest/IcebergRESTServiceOperations.java     | 62 +++++++++++----
 .../web/rest/TestIcebergRESTServiceOperations.java | 93 ++++++++++++++--------
 .../connector/catalog/CatalogConnectorManager.java | 26 +++++-
 .../trino/connector/catalog/CatalogRegister.java   | 36 ++++++++-
 .../catalog/TestCatalogConnectorManager.java       | 53 ++++++++++++
 .../connector/catalog/TestCatalogRegister.java     | 88 ++++++++++++++++++++
 .../TestIcebergCatalogPropertyConverter.java       | 40 ++++++++++
 9 files changed, 401 insertions(+), 54 deletions(-)

diff --git a/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java b/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java
index c1c0c14235..83971c9953 100644
--- a/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java
+++ b/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java
@@ -109,6 +109,24 @@ public class AuxiliaryServiceManager {
     return IsolatedClassLoader.buildClassLoader(classPaths);
   }
 
+  /**
+   * Returns the effective configuration for one auxiliary service, with keys stripped of the {@code
+   * gravitino.<name>.} prefix (or the deprecated {@code gravitino.auxService.<name>.} prefix, which
+   * is still honored) — the same map the service itself receives in {@link
+   * GravitinoAuxiliaryService#serviceInit}. Callers outside this service (e.g. reporting an
+   * auxiliary service's own endpoint) should read its config through this method rather than the
+   * raw {@code gravitino.<name>.} prefix directly, so both config forms are honored consistently.
+   *
+   * @param gravitinoConfig the Gravitino server's configuration
+   * @param auxServiceName the auxiliary service's short name, e.g. {@code iceberg-rest}
+   * @return the auxiliary service's own configuration, with keys unprefixed
+   */
+  public static Map<String, String> getAuxServiceConfig(
+      Config gravitinoConfig, String auxServiceName) {
+    Map<String, String> serviceConfigs = extractAuxiliaryServiceConfigs(gravitinoConfig);
+    return MapUtils.getPrefixMap(serviceConfigs, DOT.join(auxServiceName, ""));
+  }
+
   @VisibleForTesting
   static String getValidPath(String auxServiceName, String pathString) {
     Path path = Paths.get(pathString);
diff --git a/core/src/test/java/org/apache/gravitino/auxiliary/TestAuxiliaryServiceManager.java b/core/src/test/java/org/apache/gravitino/auxiliary/TestAuxiliaryServiceManager.java
index 5df4b897f2..0148321038 100644
--- a/core/src/test/java/org/apache/gravitino/auxiliary/TestAuxiliaryServiceManager.java
+++ b/core/src/test/java/org/apache/gravitino/auxiliary/TestAuxiliaryServiceManager.java
@@ -139,6 +139,45 @@ public class TestAuxiliaryServiceManager {
     Assertions.assertFalse(spyAuxManager.isAuxServiceRegistered("lance-rest"));
   }
 
+  @Test
+  void testGetAuxServiceConfig() {
+    DummyConfig config =
+        DummyConfig.of(
+            ImmutableMap.of(
+                AuxiliaryServiceManager.GRAVITINO_AUX_SERVICE_PREFIX
+                    + AuxiliaryServiceManager.AUX_SERVICE_NAMES,
+                "iceberg-rest",
+                "gravitino.iceberg-rest.host",
+                "irc-host",
+                "gravitino.iceberg-rest.httpPort",
+                "9001"));
+
+    Map<String, String> resolved =
+        AuxiliaryServiceManager.getAuxServiceConfig(config, "iceberg-rest");
+
+    Assertions.assertEquals("irc-host", resolved.get("host"));
+    Assertions.assertEquals("9001", resolved.get("httpPort"));
+  }
+
+  @Test
+  void testGetAuxServiceConfigHonorsDeprecatedPrefix() {
+    // gravitino.auxService.<name>.<key> is deprecated but still honored; the effective config a
+    // caller reads through this method must match what the service itself receives.
+    DummyConfig config =
+        DummyConfig.of(
+            ImmutableMap.of(
+                AuxiliaryServiceManager.GRAVITINO_AUX_SERVICE_PREFIX
+                    + AuxiliaryServiceManager.AUX_SERVICE_NAMES,
+                "iceberg-rest",
+                AuxiliaryServiceManager.GRAVITINO_AUX_SERVICE_PREFIX + "iceberg-rest.host",
+                "irc-host"));
+
+    Map<String, String> resolved =
+        AuxiliaryServiceManager.getAuxServiceConfig(config, "iceberg-rest");
+
+    Assertions.assertEquals("irc-host", resolved.get("host"));
+  }
+
   @Test
   void testAuxiliaryServiceConfigs() {
     Map<String, String> m =
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java
index f296e068db..ce672875e8 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.server.web.rest;
 
 import com.codahale.metrics.annotation.ResponseMetered;
 import com.codahale.metrics.annotation.Timed;
+import java.util.Map;
 import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.Consumes;
 import javax.ws.rs.GET;
@@ -30,12 +31,13 @@ import javax.ws.rs.core.Context;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
 import org.apache.commons.lang3.StringUtils;
-import org.apache.gravitino.Config;
 import org.apache.gravitino.GravitinoEnv;
 import org.apache.gravitino.auxiliary.AuxiliaryServiceManager;
 import org.apache.gravitino.dto.responses.IcebergRESTServiceResponse;
 import org.apache.gravitino.metrics.MetricNames;
 import org.apache.gravitino.server.web.Utils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Reports the endpoint of the Gravitino Iceberg REST server, so that clients which already connect
@@ -46,16 +48,25 @@ import org.apache.gravitino.server.web.Utils;
 @Produces(MediaType.APPLICATION_JSON)
 public class IcebergRESTServiceOperations {
 
+  private static final Logger LOG = LoggerFactory.getLogger(IcebergRESTServiceOperations.class);
+
   // Matches gravitino.auxService.names / AuxiliaryServiceManager's registration key.
   private static final String AUX_SERVICE_NAME = "iceberg-rest";
-  private static final String CONFIG_PREFIX = "gravitino.iceberg-rest.";
+  // Keys below are read from AuxiliaryServiceManager.getAuxServiceConfig, which already strips
+  // the gravitino.iceberg-rest. (or deprecated gravitino.auxService.iceberg-rest.) prefix, so
+  // they must NOT be re-prefixed here.
+  // The provider name used by the Iceberg REST server itself; see
+  // IcebergConstants.ICEBERG_REST_CATALOG_CONFIG_PROVIDER and DynamicIcebergConfigProvider. The
+  // server module cannot depend on iceberg-common/catalog-common, hence the literal here.
+  private static final String CATALOG_CONFIG_PROVIDER_KEY = "catalog-config-provider";
+  private static final String DYNAMIC_CATALOG_CONFIG_PROVIDER_NAME = "dynamic-config-provider";
   // The post-strip key used by the Iceberg REST server itself; see
   // IcebergConstants.GRAVITINO_METALAKE and DynamicIcebergConfigProvider.
-  private static final String SERVED_METALAKE_KEY = CONFIG_PREFIX + "gravitino-metalake";
-  private static final String HOST_KEY = CONFIG_PREFIX + "host";
-  private static final String HTTP_PORT_KEY = CONFIG_PREFIX + "httpPort";
-  private static final String HTTPS_PORT_KEY = CONFIG_PREFIX + "httpsPort";
-  private static final String ENABLE_HTTPS_KEY = CONFIG_PREFIX + "enableHttps";
+  private static final String SERVED_METALAKE_KEY = "gravitino-metalake";
+  private static final String HOST_KEY = "host";
+  private static final String HTTP_PORT_KEY = "httpPort";
+  private static final String HTTPS_PORT_KEY = "httpsPort";
+  private static final String ENABLE_HTTPS_KEY = "enableHttps";
   // Match IcebergConfig.DEFAULT_ICEBERG_REST_SERVICE_HTTP_PORT/HTTPS_PORT: the server module
   // cannot depend on iceberg-common, and JettyServerConfig's own defaults are the Gravitino
   // server's (8090/8433), not the Iceberg REST server's — reading raw values with these
@@ -91,8 +102,12 @@ public class IcebergRESTServiceOperations {
     return GravitinoEnv.getInstance().auxServiceManager();
   }
 
-  Config getConfig() {
-    return GravitinoEnv.getInstance().config();
+  // Resolved through AuxiliaryServiceManager.getAuxServiceConfig rather than reading
+  // gravitino.iceberg-rest.* directly, so the deprecated gravitino.auxService.iceberg-rest.*
+  // config form is honored too — the same precedence the Iceberg REST server itself sees.
+  Map<String, String> getIcebergRestServiceConfig() {
+    return AuxiliaryServiceManager.getAuxServiceConfig(
+        GravitinoEnv.getInstance().config(), AUX_SERVICE_NAME);
   }
 
   HttpServletRequest getHttpRequest() {
@@ -104,17 +119,34 @@ public class IcebergRESTServiceOperations {
       return null;
     }
 
-    Config config = getConfig();
-    String servedMetalake = config.getRawString(SERVED_METALAKE_KEY, "");
+    Map<String, String> config = getIcebergRestServiceConfig();
+    String provider = config.getOrDefault(CATALOG_CONFIG_PROVIDER_KEY, "");
+    if (!DYNAMIC_CATALOG_CONFIG_PROVIDER_NAME.equals(provider)) {
+      // Only the dynamic catalog config provider maps Iceberg REST catalog names onto Gravitino
+      // catalogs; the default static provider serves statically-declared catalogs unrelated to
+      // Gravitino catalog names, so routing at it would 404 on every request.
+      LOG.debug(
+          "Iceberg REST service does not use the dynamic catalog config provider "
+              + "(catalog-config-provider={}); not reporting its endpoint for auto-discovery.",
+          provider);
+      return null;
+    }
+
+    String servedMetalake = config.getOrDefault(SERVED_METALAKE_KEY, "");
     if (StringUtils.isNotBlank(metalake)
         && StringUtils.isNotBlank(servedMetalake)
         && !servedMetalake.equals(metalake)) {
       // The Iceberg REST server serves exactly one metalake. Routing a different metalake's
       // catalogs at it would 404 on every request, so report it as unavailable instead.
+      LOG.debug(
+          "Iceberg REST service serves metalake {}, not the requested metalake {}; not "
+              + "reporting its endpoint for auto-discovery.",
+          servedMetalake,
+          metalake);
       return null;
     }
 
-    String host = config.getRawString(HOST_KEY, DEFAULT_HOST);
+    String host = config.getOrDefault(HOST_KEY, DEFAULT_HOST);
     if (isWildcardHost(host)) {
       // The Iceberg REST server binds to all interfaces, so it has no single externally
       // reachable address of its own. The caller already reached this Gravitino server at some
@@ -123,7 +155,7 @@ public class IcebergRESTServiceOperations {
       // gravitino.iceberg.rest-uri manually.
       host = getHttpRequest().getServerName();
     }
-    boolean enableHttps = Boolean.parseBoolean(config.getRawString(ENABLE_HTTPS_KEY, "false"));
+    boolean enableHttps = Boolean.parseBoolean(config.getOrDefault(ENABLE_HTTPS_KEY, "false"));
     String scheme = enableHttps ? "https" : "http";
     int port =
         parsePort(
@@ -133,8 +165,8 @@ public class IcebergRESTServiceOperations {
     return String.format("%s://%s:%d/iceberg", scheme, host, port);
   }
 
-  private static int parsePort(Config config, String key, int defaultPort) {
-    String value = config.getRawString(key, "");
+  private static int parsePort(Map<String, String> config, String key, int defaultPort) {
+    String value = config.getOrDefault(key, "");
     if (StringUtils.isBlank(value)) {
       return defaultPort;
     }
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java
index d295f75ada..f4bb9eddb7 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java
@@ -27,26 +27,25 @@ import com.google.common.collect.ImmutableMap;
 import java.util.Map;
 import javax.servlet.http.HttpServletRequest;
 import javax.ws.rs.core.Response;
-import org.apache.gravitino.Config;
 import org.apache.gravitino.auxiliary.AuxiliaryServiceManager;
 import org.apache.gravitino.dto.responses.IcebergRESTServiceResponse;
 import org.junit.jupiter.api.Test;
 
 public class TestIcebergRESTServiceOperations {
 
-  private static class DummyConfig extends Config {
-    static DummyConfig of(Map<String, String> m) {
-      DummyConfig config = new DummyConfig();
-      config.loadFromMap(m, k -> true);
-      return config;
-    }
+  private static final String DYNAMIC_PROVIDER = "dynamic-config-provider";
+
+  private static Map<String, String> withDynamicProvider(Map<String, String> extra) {
+    return ImmutableMap.<String, String>builder()
+        .put("catalog-config-provider", DYNAMIC_PROVIDER)
+        .putAll(extra)
+        .buildKeepingLast();
   }
 
   private IcebergRESTServiceOperations newOps(
       boolean registered, Map<String, String> icebergConfig, String requestServerName) {
     AuxiliaryServiceManager auxServiceManager = mock(AuxiliaryServiceManager.class);
     when(auxServiceManager.isAuxServiceRegistered("iceberg-rest")).thenReturn(registered);
-    Config config = DummyConfig.of(icebergConfig);
     HttpServletRequest request = mock(HttpServletRequest.class);
     when(request.getServerName()).thenReturn(requestServerName);
 
@@ -57,8 +56,8 @@ public class TestIcebergRESTServiceOperations {
       }
 
       @Override
-      Config getConfig() {
-        return config;
+      Map<String, String> getIcebergRestServiceConfig() {
+        return icebergConfig;
       }
 
       @Override
@@ -78,13 +77,34 @@ public class TestIcebergRESTServiceOperations {
     assertNull(uriOf(ops.getIcebergRestServiceUri("test")));
   }
 
+  @Test
+  public void testReturnsNullWhenNotUsingDynamicConfigProvider() {
+    // Regression test: the default (static) catalog config provider serves statically-declared
+    // catalogs unrelated to Gravitino catalog names, so it must never be reported for
+    // auto-discovery — even with a blank/absent catalog-config-provider, which is what the
+    // common no-provider-configured deployment looks like.
+    IcebergRESTServiceOperations ops =
+        newOps(true, ImmutableMap.of("host", "irc-host"), "gravitino-host");
+    assertNull(uriOf(ops.getIcebergRestServiceUri("test")));
+  }
+
+  @Test
+  public void testReturnsNullWhenStaticConfigProviderExplicit() {
+    IcebergRESTServiceOperations ops =
+        newOps(
+            true,
+            ImmutableMap.of("catalog-config-provider", "static-config-provider", "host", "h"),
+            "gravitino-host");
+    assertNull(uriOf(ops.getIcebergRestServiceUri("test")));
+  }
+
   @Test
   public void testDefaultPortIsTheIcebergRestDefaultNotTheGravitinoServerDefault() {
-    // Regression test: without an explicit gravitino.iceberg-rest.httpPort, the reported port
-    // must be the Iceberg REST server's own default (9001), not the Gravitino webserver's
-    // default (8090) that JettyServerConfig would otherwise fall back to.
+    // Regression test: without an explicit httpPort, the reported port must be the Iceberg REST
+    // server's own default (9001), not the Gravitino webserver's default (8090) that
+    // JettyServerConfig would otherwise fall back to.
     IcebergRESTServiceOperations ops =
-        newOps(true, ImmutableMap.of("gravitino.iceberg-rest.host", "irc-host"), "gravitino-host");
+        newOps(true, withDynamicProvider(ImmutableMap.of("host", "irc-host")), "gravitino-host");
     assertEquals("http://irc-host:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));
   }
 
@@ -93,9 +113,10 @@ public class TestIcebergRESTServiceOperations {
     IcebergRESTServiceOperations ops =
         newOps(
             true,
-            ImmutableMap.of(
-                "gravitino.iceberg-rest.host", "irc-host",
-                "gravitino.iceberg-rest.enableHttps", "true"),
+            withDynamicProvider(
+                ImmutableMap.of(
+                    "host", "irc-host",
+                    "enableHttps", "true")),
             "gravitino-host");
     assertEquals("https://irc-host:9433/iceberg", uriOf(ops.getIcebergRestServiceUri("")));
   }
@@ -105,9 +126,10 @@ public class TestIcebergRESTServiceOperations {
     IcebergRESTServiceOperations ops =
         newOps(
             true,
-            ImmutableMap.of(
-                "gravitino.iceberg-rest.host", "irc-host",
-                "gravitino.iceberg-rest.httpPort", "19001"),
+            withDynamicProvider(
+                ImmutableMap.of(
+                    "host", "irc-host",
+                    "httpPort", "19001")),
             "gravitino-host");
     assertEquals("http://irc-host:19001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));
   }
@@ -116,16 +138,15 @@ public class TestIcebergRESTServiceOperations {
   public void testWildcardHostFallsBackToRequestServerName() {
     IcebergRESTServiceOperations ops =
         newOps(
-            true,
-            ImmutableMap.of("gravitino.iceberg-rest.host", "0.0.0.0"),
-            "host.docker.internal");
+            true, withDynamicProvider(ImmutableMap.of("host", "0.0.0.0")), "host.docker.internal");
     assertEquals(
         "http://host.docker.internal:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));
   }
 
   @Test
   public void testBlankHostIsTreatedAsWildcard() {
-    IcebergRESTServiceOperations ops = newOps(true, ImmutableMap.of(), "gravitino-host");
+    IcebergRESTServiceOperations ops =
+        newOps(true, withDynamicProvider(ImmutableMap.of()), "gravitino-host");
     assertEquals("http://gravitino-host:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));
   }
 
@@ -134,9 +155,10 @@ public class TestIcebergRESTServiceOperations {
     IcebergRESTServiceOperations ops =
         newOps(
             true,
-            ImmutableMap.of(
-                "gravitino.iceberg-rest.host", "irc-host",
-                "gravitino.iceberg-rest.gravitino-metalake", "prod"),
+            withDynamicProvider(
+                ImmutableMap.of(
+                    "host", "irc-host",
+                    "gravitino-metalake", "prod")),
             "gravitino-host");
     assertNull(uriOf(ops.getIcebergRestServiceUri("test")));
   }
@@ -146,9 +168,10 @@ public class TestIcebergRESTServiceOperations {
     IcebergRESTServiceOperations ops =
         newOps(
             true,
-            ImmutableMap.of(
-                "gravitino.iceberg-rest.host", "irc-host",
-                "gravitino.iceberg-rest.gravitino-metalake", "test"),
+            withDynamicProvider(
+                ImmutableMap.of(
+                    "host", "irc-host",
+                    "gravitino-metalake", "test")),
             "gravitino-host");
     assertEquals("http://irc-host:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("test")));
   }
@@ -158,16 +181,18 @@ public class TestIcebergRESTServiceOperations {
     IcebergRESTServiceOperations ops =
         newOps(
             true,
-            ImmutableMap.of(
-                "gravitino.iceberg-rest.host", "irc-host",
-                "gravitino.iceberg-rest.gravitino-metalake", "prod"),
+            withDynamicProvider(
+                ImmutableMap.of(
+                    "host", "irc-host",
+                    "gravitino-metalake", "prod")),
             "gravitino-host");
     assertEquals("http://irc-host:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));
   }
 
   @Test
   public void testResponseIsNotCacheable() {
-    IcebergRESTServiceOperations ops = newOps(true, ImmutableMap.of(), "gravitino-host");
+    IcebergRESTServiceOperations ops =
+        newOps(true, withDynamicProvider(ImmutableMap.of()), "gravitino-host");
     Response response = ops.getIcebergRestServiceUri("");
     assertEquals("no-store", response.getHeaderString("Cache-Control"));
   }
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java
index e11c16b30b..ce9dc5b7da 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java
@@ -73,6 +73,9 @@ public class CatalogConnectorManager {
 
   private String targetMetalake;
   private final Map<String, GravitinoMetalake> metalakes = new ConcurrentHashMap<>();
+  // Tracks which metalakes' Iceberg REST discovery is currently failing, so a failure is logged
+  // at WARN only on the transition into/out of that state rather than on every poll.
+  private final Set<String> icebergRestDiscoveryFailing = ConcurrentHashMap.newKeySet();
 
   private GravitinoAdminClient gravitinoClient;
   private GravitinoConfig config;
@@ -213,15 +216,32 @@ public class CatalogConnectorManager {
    * caches the answer on the shared {@link GravitinoConfig} for {@code IcebergConnectorAdapter} to
    * read on the next catalog load. Failures — including talking to a Gravitino server older than
    * this endpoint — must not interrupt catalog loading, so they are swallowed here; Iceberg
-   * catalogs simply keep their last known routing decision until the next successful poll.
+   * catalogs simply keep their last known routing decision until the next successful poll. A
+   * failure is logged at WARN only on the transition into that state (not on every poll), so a
+   * persistently failing/misconfigured discovery is still visible at the default log level without
+   * spamming the log for the common case of an older Gravitino server that lacks this endpoint
+   * entirely.
    */
   private void refreshIcebergRestUri(String metalakeName) {
     try {
       config.setDiscoveredIcebergRestUri(
           metalakeName, gravitinoClient.icebergRestServiceUri(metalakeName).orElse(null));
+      if (icebergRestDiscoveryFailing.remove(metalakeName)) {
+        LOG.info("Iceberg REST service discovery for metalake {} recovered.", metalakeName);
+      }
     } catch (Exception e) {
-      LOG.debug(
-          "Failed to query the Iceberg REST service endpoint for metalake {}.", metalakeName, e);
+      if (icebergRestDiscoveryFailing.add(metalakeName)) {
+        LOG.warn(
+            "Failed to query the Iceberg REST service endpoint for metalake {}; keeping the "
+                + "last known routing decision. This is expected when talking to a Gravitino "
+                + "server that predates this endpoint, but is otherwise worth investigating. "
+                + "Further failures for this metalake are logged at DEBUG until it recovers.",
+            metalakeName,
+            e);
+      } else {
+        LOG.debug(
+            "Failed to query the Iceberg REST service endpoint for metalake {}.", metalakeName, e);
+      }
     }
   }
 
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
index 35f722bb1e..4189a251cc 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
@@ -35,6 +35,8 @@ import java.sql.Statement;
 import java.util.Map;
 import java.util.Properties;
 import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.gravitino.trino.connector.GravitinoConfig;
 import org.apache.gravitino.trino.connector.GravitinoErrorCode;
@@ -60,6 +62,16 @@ public class CatalogRegister {
   private static final Set<String> SSL_VERIFICATION_MODES =
       ImmutableSet.of(SSL_VERIFICATION_FULL, SSL_VERIFICATION_CA, SSL_VERIFICATION_NONE);
 
+  // Matches "some.key.credential"='value' style property assignments (as produced by
+  // GravitinoConfig.toCatalogConfig / GravitinoCatalog.toJson-embedded WITH(...) clauses) whose
+  // key looks like it carries a secret, e.g. gravitino.iceberg.rest-catalog.oauth2.credential.
+  // Values matching this are redacted before the CREATE CATALOG statement is logged, since it can
+  // otherwise leak IRC OAuth2 client secrets and similar into the log and Trino's query history.
+  private static final Pattern SECRET_PROPERTY_PATTERN =
+      Pattern.compile(
+          "\"([^\"]*(?:credential|token|secret|password)[^\"]*)\"\\s*=\\s*'([^']*)'",
+          Pattern.CASE_INSENSITIVE);
+
   private Connection connection;
   private boolean isStarted = false;
   private String catalogStoreDirectory;
@@ -303,7 +315,15 @@ public class CatalogRegister {
     }
   }
 
-  private String generateCreateCatalogCommand(String name, GravitinoCatalog gravitinoCatalog)
+  // Package-private (rather than private) so tests can exercise the embed-then-serialize wiring
+  // without a live Trino JDBC connection, which init() otherwise requires.
+  @VisibleForTesting
+  void setConfigForTesting(GravitinoConfig config) {
+    this.config = config;
+  }
+
+  @VisibleForTesting
+  String generateCreateCatalogCommand(String name, GravitinoCatalog gravitinoCatalog)
       throws Exception {
     // This statement is replicated by Trino to every node in the cluster, coordinator and workers
     // alike, so it is the only place a value the coordinator alone knows (like the Iceberg REST
@@ -320,6 +340,18 @@ public class CatalogRegister {
         config.toCatalogConfig());
   }
 
+  @VisibleForTesting
+  static String redactSecrets(String createCatalogCommand) {
+    Matcher matcher = SECRET_PROPERTY_PATTERN.matcher(createCatalogCommand);
+    StringBuffer redacted = new StringBuffer();
+    while (matcher.find()) {
+      matcher.appendReplacement(
+          redacted, Matcher.quoteReplacement("\"" + matcher.group(1) + "\"='***'"));
+    }
+    matcher.appendTail(redacted);
+    return redacted.toString();
+  }
+
   private String generateDropCatalogCommand(String name) {
     return String.format("DROP CATALOG %s", name);
   }
@@ -356,7 +388,7 @@ public class CatalogRegister {
       }
       String createCatalogCommand = generateCreateCatalogCommand(name, catalog);
       executeSql(createCatalogCommand);
-      LOG.info("Register catalog {} successfully: {}", name, createCatalogCommand);
+      LOG.info("Register catalog {} successfully: {}", name, redactSecrets(createCatalogCommand));
     } catch (SQLException e) {
       throw new TrinoException(GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, e.getMessage(), e);
     } catch (Exception e) {
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.java
index f03cf0a474..5ac9efb5e7 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogConnectorManager.java
@@ -30,7 +30,10 @@ import static org.mockito.Mockito.when;
 import com.google.common.collect.ImmutableMap;
 import io.trino.spi.TrinoException;
 import io.trino.spi.connector.ConnectorContext;
+import java.util.Optional;
 import org.apache.gravitino.client.GravitinoAdminClient;
+import org.apache.gravitino.client.GravitinoMetalake;
+import org.apache.gravitino.exceptions.RESTException;
 import org.apache.gravitino.trino.connector.GravitinoConfig;
 import org.apache.gravitino.trino.connector.GravitinoErrorCode;
 import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
@@ -140,6 +143,56 @@ public class TestCatalogConnectorManager {
     assertFalse(manager.skipCatalog("b2"));
   }
 
+  @Test
+  public void testRefreshIcebergRestUriCachesDiscoveredUri() throws Exception {
+    GravitinoAdminClient client = mock(GravitinoAdminClient.class);
+    CatalogRegister catalogRegister = mock(CatalogRegister.class);
+    when(catalogRegister.isTrinoStarted()).thenReturn(true);
+    when(client.loadMetalake("test")).thenReturn(mock(GravitinoMetalake.class));
+    when(client.icebergRestServiceUri("test"))
+        .thenReturn(Optional.of("http://irc-host:9001/iceberg"));
+
+    CatalogConnectorManager manager =
+        new CatalogConnectorManager(catalogRegister, createCatalogConnectorFactory(), null);
+    GravitinoConfig config =
+        new GravitinoConfig(
+            ImmutableMap.of(
+                "gravitino.uri", "http://127.0.0.1:8090",
+                "gravitino.metalake", "test",
+                "gravitino.use-single-metalake", "true"));
+    manager.config(config, client);
+
+    manager.loadMetalakeSync();
+
+    assertEquals("http://irc-host:9001/iceberg", config.getDiscoveredIcebergRestUri("test"));
+  }
+
+  @Test
+  public void testRefreshIcebergRestUriSwallowsFailureAndKeepsCatalogLoadingGoing()
+      throws Exception {
+    GravitinoAdminClient client = mock(GravitinoAdminClient.class);
+    CatalogRegister catalogRegister = mock(CatalogRegister.class);
+    when(catalogRegister.isTrinoStarted()).thenReturn(true);
+    when(client.loadMetalake("test")).thenReturn(mock(GravitinoMetalake.class));
+    when(client.icebergRestServiceUri("test"))
+        .thenThrow(new RESTException("simulated: endpoint not found on an older server"));
+
+    CatalogConnectorManager manager =
+        new CatalogConnectorManager(catalogRegister, createCatalogConnectorFactory(), null);
+    GravitinoConfig config =
+        new GravitinoConfig(
+            ImmutableMap.of(
+                "gravitino.uri", "http://127.0.0.1:8090",
+                "gravitino.metalake", "test",
+                "gravitino.use-single-metalake", "true"));
+    manager.config(config, client);
+
+    // A discovery failure must not abort the metalake load (which loads catalogs), and must
+    // leave the discovered URI at its previous value rather than throwing out of loadMetalake.
+    assertDoesNotThrow(manager::loadMetalakeSync);
+    assertEquals("", config.getDiscoveredIcebergRestUri("test"));
+  }
+
   private CatalogConnectorManager createManager(ImmutableMap<String, String> configMap)
       throws Exception {
     return createManager(createCatalogConnectorFactory(), configMap);
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java
index 2effd98843..488cfc7ed6 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java
@@ -26,14 +26,19 @@ import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
+import com.google.common.collect.ImmutableMap;
 import io.trino.spi.TrinoException;
 import java.io.IOException;
 import java.nio.file.Files;
 import java.nio.file.Path;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.Map;
 import java.util.Properties;
+import org.apache.gravitino.Catalog;
 import org.apache.gravitino.trino.connector.GravitinoConfig;
+import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
+import org.apache.gravitino.trino.connector.metadata.TestGravitinoCatalog;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.io.TempDir;
 
@@ -377,4 +382,87 @@ public class TestCatalogRegister {
     assertTrue(e.getMessage().contains("does not exist"));
     assertTrue(e.getMessage().contains("trino.jdbc.ssl.truststore.path"));
   }
+
+  private static final String DISCOVERED_ICEBERG_REST_URI_PROPERTY = "__gravitino.iceberg.rest-uri";
+
+  @Test
+  public void testGenerateCreateCatalogCommandEmbedsDiscoveredUriForIcebergCatalog()
+      throws Exception {
+    GravitinoConfig config =
+        new GravitinoConfig(
+            ImmutableMap.of(
+                "gravitino.uri", "http://127.0.0.1:8090", "gravitino.metalake", "test"));
+    config.setDiscoveredIcebergRestUri("test", "http://irc-host:9001/iceberg");
+
+    CatalogRegister catalogRegister = new CatalogRegister();
+    catalogRegister.setConfigForTesting(config);
+
+    Catalog mockCatalog =
+        TestGravitinoCatalog.mockCatalog(
+            "iceberg_catalog",
+            "lakehouse-iceberg",
+            "test catalog",
+            Catalog.Type.RELATIONAL,
+            Collections.emptyMap());
+    GravitinoCatalog catalog = new GravitinoCatalog("test", mockCatalog);
+
+    String command = catalogRegister.generateCreateCatalogCommand("iceberg_catalog", catalog);
+
+    assertTrue(
+        command.contains(
+            "\"" + DISCOVERED_ICEBERG_REST_URI_PROPERTY + "\":\"http://irc-host:9001/iceberg\""),
+        "Expected the discovered Iceberg REST URI to be embedded in: " + command);
+  }
+
+  @Test
+  public void testGenerateCreateCatalogCommandDoesNotEmbedUriForNonIcebergCatalog()
+      throws Exception {
+    // The discovered URI is per-Iceberg-catalog routing state; embedding it into every catalog's
+    // properties (e.g. a Hive catalog) would be a leaky abstraction and is guarded against in
+    // IcebergConnectorAdapter.embedDiscoveredIcebergRestUri. This asserts that guard actually
+    // takes effect when reached through CatalogRegister, not just when called directly.
+    GravitinoConfig config =
+        new GravitinoConfig(
+            ImmutableMap.of(
+                "gravitino.uri", "http://127.0.0.1:8090", "gravitino.metalake", "test"));
+    config.setDiscoveredIcebergRestUri("test", "http://irc-host:9001/iceberg");
+
+    CatalogRegister catalogRegister = new CatalogRegister();
+    catalogRegister.setConfigForTesting(config);
+
+    Catalog mockCatalog =
+        TestGravitinoCatalog.mockCatalog(
+            "hive_catalog",
+            "hive",
+            "test catalog",
+            Catalog.Type.RELATIONAL,
+            Collections.emptyMap());
+    GravitinoCatalog catalog = new GravitinoCatalog("test", mockCatalog);
+
+    String command = catalogRegister.generateCreateCatalogCommand("hive_catalog", catalog);
+
+    assertFalse(command.contains(DISCOVERED_ICEBERG_REST_URI_PROPERTY));
+  }
+
+  @Test
+  public void testRedactSecretsMasksSecretBearingProperties() {
+    String command =
+        "CREATE CATALOG c USING gravitino WITH ( "
+            + "\"gravitino.iceberg.rest-catalog.oauth2.credential\"='client:secretvalue', "
+            + "\"gravitino.iceberg.rest-catalog.uri\"='http://irc-host:9001/iceberg', "
+            + "\"some.token\"='abc123', "
+            + "\"trino.bypass.password\"='hunter2')";
+
+    String redacted = CatalogRegister.redactSecrets(command);
+
+    assertFalse(redacted.contains("secretvalue"));
+    assertFalse(redacted.contains("abc123"));
+    assertFalse(redacted.contains("hunter2"));
+    assertTrue(redacted.contains("\"gravitino.iceberg.rest-catalog.oauth2.credential\"='***'"));
+    assertTrue(redacted.contains("\"some.token\"='***'"));
+    assertTrue(redacted.contains("\"trino.bypass.password\"='***'"));
+    // Non-secret properties must survive redaction unchanged.
+    assertTrue(
+        redacted.contains("\"gravitino.iceberg.rest-catalog.uri\"='http://irc-host:9001/iceberg'"));
+  }
 }
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
index ee3e448c29..1951003a19 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
@@ -426,6 +426,46 @@ public class TestIcebergCatalogPropertyConverter {
     Assertions.assertNull(config.get("iceberg.rest-catalog.uri"));
   }
 
+  @Test
+  public void testManualUriWinsOverDiscoveredUri() throws Exception {
+    // Both a manual gravitino.iceberg.rest-uri and a discovered per-metalake URI are set; the
+    // manual override must win, matching IcebergConnectorAdapter.buildInternalConnectorConfig's
+    // documented precedence.
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .put("catalog-backend", "jdbc")
+            .put("uri", "jdbc:postgresql://localhost:5432/iceberg")
+            .put("jdbc-driver", "org.postgresql.Driver")
+            .build();
+
+    GravitinoConfig config = icebergRestConfiguredConfig(ImmutableMap.of());
+    config.setDiscoveredIcebergRestUri("test", "http://discovered:9001/iceberg");
+
+    Map<String, String> connectorConfig =
+        buildConnectorConfig("catalog1", properties, config, /* embedDiscovery= */ true);
+
+    Assertions.assertEquals("rest", connectorConfig.get("iceberg.catalog.type"));
+    Assertions.assertEquals(
+        "http://localhost:9001/iceberg", connectorConfig.get("iceberg.rest-catalog.uri"));
+  }
+
+  @Test
+  public void testEmbedDiscoveredIcebergRestUriDoesNotAffectNonIcebergCatalog() {
+    // CatalogRegister calls embedDiscoveredIcebergRestUri unconditionally for every catalog being
+    // registered, not just Iceberg ones, so this guard is load-bearing: a Hive/MySQL/etc. catalog
+    // must never end up carrying the synthetic discovered-URI property.
+    GravitinoConfig config = icebergRestDiscoveredConfig("test", "http://discovered:9001/iceberg");
+    Catalog mockHiveCatalog =
+        TestGravitinoCatalog.mockCatalog(
+            "hive_catalog", "hive", "test catalog", Catalog.Type.RELATIONAL, ImmutableMap.of());
+    GravitinoCatalog hiveCatalog = new GravitinoCatalog("test", mockHiveCatalog);
+
+    GravitinoCatalog result =
+        IcebergConnectorAdapter.embedDiscoveredIcebergRestUri(hiveCatalog, config);
+
+    Assertions.assertEquals(hiveCatalog.getProperties(), result.getProperties());
+  }
+
   @Test
   public void testBuildConnectorPropertiesWithIcebergRestAuthentication() throws Exception {
     Map<String, String> properties =


(gravitino) 01/13: [Cherry-pick to branch-1.3] Feature/trino connector oauth2 user forwarding (#12045)

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diqiu50 pushed a commit to branch trino-irc-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit 3484805201550e2a119a9232bcc44c40ddf40a2f
Author: Mark Hoerth <47...@users.noreply.github.com>
AuthorDate: Mon Aug 17 00:31:12 2026 -0700

    [Cherry-pick to branch-1.3] Feature/trino connector oauth2 user forwarding (#12045)
---
 docs/trino-connector/authentication.md             | 211 +++++++++++++++++----
 .../service/IcebergCatalogWrapperManager.java      |   4 +
 .../authentication/AuthenticationFilter.java       |  11 ++
 .../trino/connector/GravitinoConnector.java        |  79 ++++++--
 .../iceberg/IcebergCatalogPropertyConverter.java   |  12 +-
 .../connector/security/GravitinoAuthProvider.java  |  58 +++++-
 .../security/StaticUserTokenProvider.java          |  54 ++++++
 .../TestGravitinoConnectorForwardUser.java         | 171 ++++++++++++++++-
 .../TestIcebergCatalogPropertyConverter.java       |  27 +++
 .../security/TestGravitinoAuthProvider.java        |  59 ++++++
 10 files changed, 620 insertions(+), 66 deletions(-)

diff --git a/docs/trino-connector/authentication.md b/docs/trino-connector/authentication.md
index 5ec6de6018..9793e7749f 100644
--- a/docs/trino-connector/authentication.md
+++ b/docs/trino-connector/authentication.md
@@ -11,6 +11,8 @@ The Gravitino Trino connector supports authenticating to the Gravitino server us
 
 If `gravitino.client.authType` is not set, the connector operates in no-authentication mode and connects to the Gravitino server without any credentials.
 
+## Authentication Types
+
 ### Simple Authentication
 
 Simple authentication uses a username to authenticate with the Gravitino server.
@@ -90,32 +92,6 @@ gravitino.client.oauth2.scope=gravitino
 | `gravitino.client.oauth2.path`       | OAuth2 token endpoint path                                      | (none)        | Yes if authType is `oauth2` |
 | `gravitino.client.oauth2.scope`      | OAuth2 scope                                                    | (none)        | Yes if authType is `oauth2` |
 
-### Kerberos Authentication
-
-Kerberos authentication uses Kerberos tickets to authenticate with the Gravitino server.
-
-**Configuration in `etc/catalog/gravitino.properties`:**
-
-```properties
-connector.name=gravitino
-gravitino.metalake=metalake
-gravitino.uri=http://localhost:8090
-
-# Kerberos authentication with keytab
-gravitino.client.authType=kerberos
-gravitino.client.kerberos.principal=user@REALM
-gravitino.client.kerberos.keytabFilePath=/path/to/user.keytab
-```
-
-**Configuration properties:**
-
-| Property                                   | Description                                                     | Default value | Required                                |
-|--------------------------------------------|-----------------------------------------------------------------|---------------|-----------------------------------------|
-| `gravitino.client.authType`                | Authentication type: `simple`, `basic`, `oauth2`, or `kerberos` | (none)        | Yes (to enable Kerberos)                |
-| `gravitino.client.kerberos.principal`      | Kerberos principal                                              | (none)        | Yes if authType is `kerberos`           |
-| `gravitino.client.kerberos.keytabFilePath` | Path to keytab file                                             | (none)        | No (uses ticket cache if not specified) |
-
-
 ### Example: Connecting to OAuth-Protected Gravitino Server
 
 This example shows how to configure the Trino connector to connect to a Gravitino server protected by OAuth authentication.
@@ -151,11 +127,36 @@ gravitino.client.oauth2.scope=test
 SHOW CATALOGS;
 ```
 
-### Session Credential Forwarding
+### Kerberos Authentication
+
+Kerberos authentication uses Kerberos tickets to authenticate with the Gravitino server.
+
+**Configuration in `etc/catalog/gravitino.properties`:**
+
+```properties
+connector.name=gravitino
+gravitino.metalake=metalake
+gravitino.uri=http://localhost:8090
+
+# Kerberos authentication with keytab
+gravitino.client.authType=kerberos
+gravitino.client.kerberos.principal=user@REALM
+gravitino.client.kerberos.keytabFilePath=/path/to/user.keytab
+```
+
+**Configuration properties:**
+
+| Property                                     | Description                                                         | Default value   | Required                                  | Since version   |
+|----------------------------------------------|---------------------------------------------------------------------|-----------------|-------------------------------------------|-----------------|
+| `gravitino.client.authType`                  | Authentication type: `simple`, `basic`, `oauth2`, or `kerberos`     | (none)          | Yes (to enable Kerberos)                  | 1.3.0           |
+| `gravitino.client.kerberos.principal`        | Kerberos principal                                                  | (none)          | Yes if authType is `kerberos`             | 1.3.0           |
+| `gravitino.client.kerberos.keytabFilePath`   | Path to keytab file                                                 | (none)          | No (uses ticket cache if not specified)   | 1.3.0           |
 
-Setting `gravitino.client.session.forwardUser=true` with `authType=simple` creates a dedicated Gravitino client per Trino session user, so each user is visible in the Gravitino audit log instead of the shared `gravitino.user`.
+## Session Credential Forwarding
 
-**Configuration:**
+Setting `gravitino.client.session.forwardUser=true` creates a dedicated Gravitino client per Trino session user, so each user is visible in the Gravitino audit log instead of the shared `gravitino.user` or service identity. It is supported with `authType=simple` and `authType=oauth2`.
+
+**Configuration (`authType=simple`):**
 
 ```properties
 connector.name=gravitino
@@ -166,22 +167,160 @@ gravitino.client.authType=simple
 gravitino.client.session.forwardUser=true
 ```
 
+With `authType=simple`, the Trino session username is forwarded to Gravitino as the simple-auth identity.
+
+**Configuration (`authType=oauth2`):**
+
+```properties
+connector.name=gravitino
+gravitino.metalake=metalake
+gravitino.uri=http://localhost:8090
+
+gravitino.client.authType=oauth2
+gravitino.client.oauth2.serverUri=http://oauth-server:8080
+gravitino.client.oauth2.credential=client_id:client_secret
+gravitino.client.oauth2.path=oauth2/token
+gravitino.client.oauth2.scope=gravitino
+gravitino.client.session.forwardUser=true
+```
+
+With `authType=oauth2`, the end user's IdP access token is presented to Gravitino directly instead of the shared client-credentials identity. This requires the Trino coordinator to populate the session's extra-credentials with the caller's access token under the key `token`; the connector reads it from there, and `buildForSession` fails with a clear error if it's missing.
+
+Whether the coordinator can populate this extra-credential depends on the Trino distribution:
+
+- **Starburst Enterprise** supports this via `http-server.authentication.type=DELEGATED-OAUTH2` — see [OAuth 2.0 token pass-through](https://docs.starburst.io/latest/security/oauth2-passthrough.html).
+- **Open-source Trino does not support this yet.** There is no equivalent coordinator-side mechanism to forward the caller's OAuth2 token into the connector session; see [trinodb/trino discussion #24403](https://github.com/trinodb/trino/discussions/24403) and [issue #27917](https://github.com/trinodb/trino/issues/27917) tracking this feature request upstream.
+
+The `gravitino.client.oauth2.*` properties above still configure the shared bootstrap/admin client used for catalog discovery — they are unrelated to the per-user forwarded token.
+
+For an Iceberg catalog with `catalog-backend=rest` (backed by an Iceberg REST Catalog), the connector does not set `iceberg.rest-catalog.security`/`iceberg.rest-catalog.session` on its own — that catalog's own `gravitino.client.*` config is unrelated to how its underlying Iceberg REST catalog authenticates. To also forward the end user's token to the REST catalog itself, set `trino.bypass.iceberg.rest-catalog.security=OAUTH2` and `trino.bypass.iceberg.rest-catalog.session=USER` explicitl [...]
+
 **Configuration properties:**
 
-| Property                                                  | Description                                                                                | Default value | Required |
-|-----------------------------------------------------------|--------------------------------------------------------------------------------------------|---------------|----------|
-| `gravitino.client.session.forwardUser`                    | When `true` with `authType=simple`, forwards the Trino session user to Gravitino per-query | `false`       | No       |
-| `gravitino.client.session.cache.maxSize`                  | Maximum number of per-user sessions to keep in the cache                                   | `500`         | No       |
-| `gravitino.client.session.cache.expireAfterAccessSeconds` | Seconds before an idle per-user session is evicted from the cache                          | `3600`        | No       |
+| Property                                                     | Description                                                                                    | Default value   | Required   | Since version   |
+|--------------------------------------------------------------|--------------------------------------------------------------------------------------------------|-----------------|------------|-----------------|
+| `gravitino.client.session.forwardUser`                       | When `true` with `authType=simple` or `authType=oauth2`, forwards the Trino session user/token to Gravitino per-query   | `false`         | No         | 1.3.0           |
+| `gravitino.client.session.cache.maxSize`                     | Maximum number of per-user sessions to keep in the cache                                       | `500`           | No         | 1.3.0           |
+| `gravitino.client.session.cache.expireAfterAccessSeconds`    | Seconds before an idle per-user session is evicted from the cache                              | `3600`          | No         | 1.3.0           |
+
+### Example: OAuth2 Per-User Token Forwarding
+
+This example walks through a full setup where each Trino user's own OAuth2 access token is
+forwarded to Gravitino and to an Iceberg REST catalog (IRC), instead of a single shared service
+identity.
+
+**1. Trino coordinator: forward the logged-in user's token to connectors.** This is the
+prerequisite that makes `authType=oauth2` forwarding possible at all — the coordinator must
+populate the session's extra-credentials with the caller's access token under the key `token`.
+
+- **Starburst Enterprise**: set the following in `etc/config.properties`:
+
+  ```properties
+  http-server.authentication.type=DELEGATED-OAUTH2
+  ```
+
+  See [OAuth 2.0 token pass-through](https://docs.starburst.io/latest/security/oauth2-passthrough.html)
+  for details, including its limitation that pass-through tokens are not refreshed and must
+  outlive the query.
+
+- **Open-source Trino**: there is currently no equivalent coordinator setting. Track
+  [trinodb/trino discussion #24403](https://github.com/trinodb/trino/discussions/24403) and
+  [issue #27917](https://github.com/trinodb/trino/issues/27917) for this feature request. Until
+  it lands upstream, this connector's `authType=oauth2` forwardUser path requires a Trino
+  distribution that provides this extra-credential itself.
+
+**2. Gravitino server: enable OAuth2** (in `conf/gravitino.conf`):
+
+```properties
+gravitino.authenticators=oauth
+gravitino.authenticator.oauth.serviceAudience=account
+gravitino.authenticator.oauth.jwksUri=http://your-idp/realms/gravitino/protocol/openid-connect/certs
+gravitino.authenticator.oauth.tokenValidatorClass=org.apache.gravitino.server.authentication.JwksTokenValidator
+gravitino.authenticator.oauth.principalFields=preferred_username,email,sub
+```
+
+**3. Trino connector: enable OAuth2 forwarding** (in `etc/catalog/gravitino.properties`):
+
+```properties
+connector.name=gravitino
+gravitino.metalake=my_metalake
+gravitino.uri=http://localhost:8090
+
+gravitino.client.authType=oauth2
+gravitino.client.oauth2.serverUri=http://your-idp
+gravitino.client.oauth2.credential=service-account-id:service-account-secret
+gravitino.client.oauth2.path=realms/gravitino/protocol/openid-connect/token
+gravitino.client.oauth2.scope=email
+gravitino.client.session.forwardUser=true
+```
+
+The `gravitino.client.oauth2.*` properties configure the shared service identity used for catalog
+discovery; the per-user forwarded token (from step 1) is what each query actually authenticates
+with once `forwardUser=true`.
+
+**4. Create the metalake and catalog.** Create the metalake `my_metalake` first (via the
+Gravitino REST API, SDK, or CLI — see
+[Manage metalakes](../manage-metalake-using-gravitino.md#create-a-metalake)), then create a
+REST-backed Iceberg catalog under it from the Trino CLI using the
+`gravitino.system.create_catalog` procedure. To also forward the end user's token to the Iceberg
+REST catalog (IRC) itself, set `trino.bypass.iceberg.rest-catalog.security=OAUTH2` and
+`trino.bypass.iceberg.rest-catalog.session=USER` on the catalog, alongside its bootstrap
+`trino.bypass.iceberg.rest-catalog.oauth2.*` credentials:
+
+```sql
+call gravitino.system.create_catalog(
+    'my_catalog',
+    'lakehouse-iceberg',
+    map(
+        array['uri', 'catalog-backend', 'warehouse',
+          'trino.bypass.iceberg.rest-catalog.security', 'trino.bypass.iceberg.rest-catalog.session',
+          'trino.bypass.iceberg.rest-catalog.oauth2.credential', 'trino.bypass.iceberg.rest-catalog.oauth2.scope',
+          'trino.bypass.iceberg.rest-catalog.oauth2.server-uri'
+        ],
+        array['http://irc-host:9001/iceberg', 'rest', 'my_catalog',
+          'OAUTH2', 'USER',
+          'service-account-id:service-account-secret', 'email',
+          'http://your-idp/realms/gravitino/protocol/openid-connect/token'
+        ]
+    )
+);
+```
+
+This call itself runs with the connector's own shared service identity, not any forwarded user
+token — `forwardUser` only affects `SELECT`/`SHOW`-style queries against the catalog afterward,
+not catalog registration itself. `create_catalog` both creates the catalog in Gravitino and loads
+it into Trino as its own top-level catalog — not as a schema nested under a single `gravitino`
+catalog. If the two `trino.bypass.iceberg.rest-catalog.*` properties above are omitted, the REST
+catalog keeps its own default security setting, independent of
+`gravitino.client.session.forwardUser`, and the end user's token never reaches the IRC.
+
+**5. Query as a specific user.** With a real OIDC login flow, Trino populates the forwarded token
+automatically after the user signs in — this automatic population is the part that requires
+Starburst's DELEGATED-OAUTH2 (step 1). For manual testing on any Trino distribution, including
+open-source Trino, the same extra-credential can instead be set directly on the CLI, independent
+of how the coordinator is configured:
+
+```shell
+trino --server http://localhost:8080 \
+  --user alice \
+  --extra-credential token=<alice-idp-access-token> \
+  --execute "SHOW SCHEMAS IN my_catalog"
+```
+
+Gravitino sees this request as `alice`, not the shared service identity — `alice`'s own
+privileges apply, and a request with a missing or invalid token is rejected before it reaches the
+catalog. Because `my_catalog` was created with `trino.bypass.iceberg.rest-catalog.session=USER`
+in step 4, the same forwarded token also reaches the IRC directly, so per-user authorization
+applies consistently whether Trino talks to Gravitino's native API or straight to the IRC.
 
-### Notes
+## Notes
 
 - The Gravitino server must be configured with the corresponding authentication mechanism enabled.
 - For OAuth2 authentication, ensure the OAuth2 server is accessible from the Trino coordinator and workers.
 - For Kerberos authentication, ensure the Kerberos configuration is properly set up on all Trino nodes.
 - Authentication configuration is passed through the `gravitino.client.*` prefix to the underlying Gravitino Java client.
 
-### See Also
+## See Also
 
 - [Gravitino Server Authentication Configuration](../security/how-to-authenticate.md)
 - [Local users and groups](../security/local-users-and-groups.md)
diff --git a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergCatalogWrapperManager.java b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergCatalogWrapperManager.java
index f9561e3f8f..ce2df6910a 100644
--- a/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergCatalogWrapperManager.java
+++ b/iceberg/iceberg-rest-server/src/main/java/org/apache/gravitino/iceberg/service/IcebergCatalogWrapperManager.java
@@ -100,6 +100,10 @@ public class IcebergCatalogWrapperManager implements AutoCloseable {
   }
 
   public CatalogWrapperForREST getCatalogWrapper(String catalogName) {
+    if (LOG.isDebugEnabled()) {
+      boolean cacheHit = catalogWrapperCache.getIfPresent(catalogName) != null;
+      LOG.debug("getCatalogWrapper catalogName={} cacheHit={}", catalogName, cacheHit);
+    }
     CatalogWrapperForREST catalogWrapperForREST =
         catalogWrapperCache.get(catalogName, k -> createCatalogWrapper(catalogName));
     // Reload conf to reset UserGroupInformation or icebergTableOps will always use
diff --git a/server-common/src/main/java/org/apache/gravitino/server/authentication/AuthenticationFilter.java b/server-common/src/main/java/org/apache/gravitino/server/authentication/AuthenticationFilter.java
index e8b100af22..c5c730dbbe 100644
--- a/server-common/src/main/java/org/apache/gravitino/server/authentication/AuthenticationFilter.java
+++ b/server-common/src/main/java/org/apache/gravitino/server/authentication/AuthenticationFilter.java
@@ -39,9 +39,13 @@ import org.apache.gravitino.exceptions.UnauthorizedException;
 import org.apache.gravitino.server.web.HealthCheckPathMatcher;
 import org.apache.gravitino.server.web.ObjectMapperProvider;
 import org.apache.gravitino.utils.PrincipalUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 public class AuthenticationFilter implements Filter {
 
+  private static final Logger LOG = LoggerFactory.getLogger(AuthenticationFilter.class);
+
   private final List<Authenticator> filterAuthenticators;
 
   /**
@@ -97,6 +101,13 @@ public class AuthenticationFilter implements Filter {
           }
         }
       }
+      if (LOG.isDebugEnabled()) {
+        LOG.debug(
+            "uri={} hasAuthHeader={} principal={}",
+            req.getRequestURI(),
+            authData != null,
+            principal == null ? "null" : principal.getName());
+      }
       if (principal == null) {
         throw new UnauthorizedException("The provided credentials did not support");
       }
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector.java
index 01d419d1fe..e038f9671e 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector.java
@@ -18,13 +18,16 @@
  */
 package org.apache.gravitino.trino.connector;
 
+import static io.trino.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
 import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;
 import static io.trino.spi.StandardErrorCode.PERMISSION_DENIED;
 
+import com.google.common.annotations.VisibleForTesting;
 import com.google.common.base.Preconditions;
 import com.google.common.cache.Cache;
 import com.google.common.cache.CacheBuilder;
 import com.google.common.cache.RemovalNotification;
+import com.google.common.util.concurrent.UncheckedExecutionException;
 import io.trino.spi.TrinoException;
 import io.trino.spi.connector.Connector;
 import io.trino.spi.connector.ConnectorAccessControl;
@@ -225,37 +228,82 @@ public class GravitinoConnector implements Connector {
     catalogConnectorContext.close();
   }
 
-  private CatalogConnectorMetadata resolveSessionMetadata(ConnectorSession session) {
-    String credKey = "simple:" + session.getUser();
+  @VisibleForTesting
+  CatalogConnectorMetadata resolveSessionMetadata(ConnectorSession session) {
+    String authType =
+        catalogConnectorContext
+            .getConfig()
+            .getClientConfig()
+            .getOrDefault(GravitinoAuthProvider.AUTH_TYPE_KEY, "simple");
+    String credentialKey =
+        catalogConnectorContext
+            .getConfig()
+            .getClientConfig()
+            .getOrDefault(
+                GravitinoAuthProvider.USER_TOKEN_CREDENTIAL_KEY,
+                GravitinoAuthProvider.DEFAULT_USER_TOKEN_CREDENTIAL_KEY);
+    String token = session.getIdentity().getExtraCredentials().get(credentialKey);
+    String credKey = sessionCacheKey(authType, session.getUser(), token);
     try {
       return perUserSessionCache.get(
               credKey,
               () -> {
-                GravitinoAdminClient userClient =
-                    GravitinoAuthProvider.buildForSession(
-                        catalogConnectorContext.getConfig(), session);
+                GravitinoAdminClient userClient = buildAuthClient(session);
                 GravitinoMetalake userMetalake =
                     userClient.loadMetalake(catalogConnectorContext.getMetalake().name());
                 return new UserSession(
                     userClient, new CatalogConnectorMetadata(userMetalake, catalogIdentifier));
               })
           .metadata;
-    } catch (ExecutionException e) {
-      Throwable cause = e.getCause();
+    } catch (ExecutionException | UncheckedExecutionException e) {
+      Throwable cause = e.getCause() == null ? e : e.getCause();
       LOG.warn(
-          "Failed to create per-user Gravitino client for user '{}': {}",
-          session.getUser(),
-          cause.getMessage());
+          "Failed to create per-user Gravitino client for user '{}'", session.getUser(), cause);
+      if (cause instanceof TrinoException) {
+        // Already carries a specific Trino error code (e.g. from buildForSession); re-wrapping
+        // would swallow it.
+        throw (TrinoException) cause;
+      }
+      if (cause instanceof IllegalArgumentException
+          || cause instanceof UnsupportedOperationException) {
+        throw new TrinoException(
+            PERMISSION_DENIED,
+            "Failed to authenticate user '"
+                + session.getUser()
+                + "' with Gravitino: "
+                + cause.getMessage(),
+            cause);
+      }
       throw new TrinoException(
-          PERMISSION_DENIED,
-          "Failed to authenticate user '"
+          GENERIC_INTERNAL_ERROR,
+          "Unexpected error while creating per-user Gravitino client for user '"
               + session.getUser()
-              + "' with Gravitino: "
+              + "': "
               + cause.getMessage(),
           cause);
     }
   }
 
+  /**
+   * Builds the per-user Gravitino admin client for a forwarded session. Extracted as an overridable
+   * seam so tests can substitute the client-building behavior without needing to mock the static
+   * {@link GravitinoAuthProvider#buildForSession}.
+   *
+   * @param session the current Trino connector session
+   * @return the per-user Gravitino admin client
+   */
+  @VisibleForTesting
+  GravitinoAdminClient buildAuthClient(ConnectorSession session) {
+    return GravitinoAuthProvider.buildForSession(catalogConnectorContext.getConfig(), session);
+  }
+
+  @VisibleForTesting
+  static String sessionCacheKey(String authType, String user, String token) {
+    String tokenPart =
+        StringUtils.isBlank(token) ? "" : ":" + Integer.toHexString(token.hashCode());
+    return authType + ":" + user + tokenPart;
+  }
+
   private Cache<String, UserSession> buildSessionCache(GravitinoConfig config) {
     Map<String, String> clientConfig = config.getClientConfig();
     String authTypeStr = clientConfig.get(GravitinoAuthProvider.AUTH_TYPE_KEY);
@@ -265,10 +313,11 @@ public class GravitinoConnector implements Connector {
           "gravitino.client.session.forwardUser=true requires gravitino.client.authType to be set");
     }
     GravitinoAuthProvider.AuthType authType = GravitinoAuthProvider.parseAuthType(authTypeStr);
-    if (authType != GravitinoAuthProvider.AuthType.SIMPLE) {
+    if (authType != GravitinoAuthProvider.AuthType.SIMPLE
+        && authType != GravitinoAuthProvider.AuthType.OAUTH2) {
       throw new TrinoException(
           GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT,
-          "gravitino.client.session.forwardUser=true only supports authType=simple, got: "
+          "gravitino.client.session.forwardUser=true only supports authType=simple or oauth2, got: "
               + authTypeStr);
     }
 
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
index 8cbb46185c..7f5460cbf0 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
@@ -156,9 +156,13 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
           "Missing required property for Rest backend: " + missingProperty);
     }
 
-    Map<String, String> jdbcProperties = new HashMap<>();
-    jdbcProperties.put("iceberg.catalog.type", "rest");
-    jdbcProperties.put("iceberg.rest-catalog.uri", properties.get(IcebergConstants.URI));
-    return jdbcProperties;
+    Map<String, String> restProperties = new HashMap<>();
+    restProperties.put("iceberg.catalog.type", "rest");
+    restProperties.put("iceberg.rest-catalog.uri", properties.get(IcebergConstants.URI));
+    if (properties.containsKey(IcebergConstants.WAREHOUSE)) {
+      restProperties.put(
+          "iceberg.rest-catalog.warehouse", properties.get(IcebergConstants.WAREHOUSE));
+    }
+    return restProperties;
   }
 }
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/security/GravitinoAuthProvider.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/security/GravitinoAuthProvider.java
index 21e2e25604..2f68a9a7b4 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/security/GravitinoAuthProvider.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/security/GravitinoAuthProvider.java
@@ -19,6 +19,7 @@
 package org.apache.gravitino.trino.connector.security;
 
 import com.google.common.base.Preconditions;
+import io.trino.spi.TrinoException;
 import io.trino.spi.connector.ConnectorSession;
 import java.io.File;
 import java.util.Locale;
@@ -29,6 +30,7 @@ import org.apache.gravitino.client.GravitinoAdminClient;
 import org.apache.gravitino.client.GravitinoClientConfiguration;
 import org.apache.gravitino.client.KerberosTokenProvider;
 import org.apache.gravitino.trino.connector.GravitinoConfig;
+import org.apache.gravitino.trino.connector.GravitinoErrorCode;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
@@ -55,6 +57,18 @@ public class GravitinoAuthProvider {
   public static final String FORWARD_SESSION_USER_KEY =
       GravitinoClientConfiguration.GRAVITINO_CLIENT_CONFIG_PREFIX + "session.forwardUser";
 
+  /**
+   * Configuration key naming the Trino session extra-credential that carries the end user's
+   * forwarded IdP access token. Defaults to {@value #DEFAULT_USER_TOKEN_CREDENTIAL_KEY}. Query
+   * engines differ in how they label the forwarded token, so this is configurable rather than
+   * fixed.
+   */
+  public static final String USER_TOKEN_CREDENTIAL_KEY =
+      "gravitino.client.session.userTokenCredentialKey";
+
+  /** Default extra-credential name used when {@link #USER_TOKEN_CREDENTIAL_KEY} is not set. */
+  public static final String DEFAULT_USER_TOKEN_CREDENTIAL_KEY = "token";
+
   /** Built-in IdP username configuration key for Basic authentication. */
   public static final String BASIC_USERNAME_KEY =
       GravitinoClientConfiguration.GRAVITINO_CLIENT_CONFIG_PREFIX + "basic.username";
@@ -165,8 +179,10 @@ public class GravitinoAuthProvider {
    * connector session. This is the entry point for the per-user client cache when {@code
    * forwardUser=true}.
    *
-   * <p>Currently only {@code authType=simple} is supported: the Trino session username is used as
-   * the Gravitino simple-auth identity.
+   * <p>For {@code authType=simple} the Trino session username is used as the Gravitino simple-auth
+   * identity. For {@code authType=oauth2} the end-user IdP token forwarded into the connector
+   * session (extra-credential key {@code token}) is presented to Gravitino as the bearer token, so
+   * the server authorizes against the end user rather than a shared service identity.
    *
    * @param config the Gravitino connector configuration
    * @param session the current Trino connector session
@@ -196,13 +212,38 @@ public class GravitinoAuthProvider {
 
     GravitinoAdminClient.AdminClientBuilder builder = GravitinoAdminClient.builder(uri);
 
-    if (authType != AuthType.SIMPLE) {
-      throw new UnsupportedOperationException(
-          "Auth type "
-              + authType
-              + " does not support session forwarding. Only simple is supported.");
+    switch (authType) {
+      case SIMPLE:
+        builder.withSimpleAuth(session.getUser());
+        break;
+      case OAUTH2:
+        {
+          String credentialKey =
+              clientConfig.getOrDefault(
+                  USER_TOKEN_CREDENTIAL_KEY, DEFAULT_USER_TOKEN_CREDENTIAL_KEY);
+          String userToken = session.getIdentity().getExtraCredentials().get(credentialKey);
+          if (StringUtils.isBlank(userToken)) {
+            throw new TrinoException(
+                GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT,
+                "No forwarded user token found in session extra-credentials under key '"
+                    + credentialKey
+                    + "'. The Trino coordinator must populate this extra-credential with the "
+                    + "caller's OAuth2 access token, e.g. Starburst Enterprise's "
+                    + "http-server.authentication.type=DELEGATED-OAUTH2; open-source Trino does not "
+                    + "support this yet. If the coordinator labels the forwarded token differently, "
+                    + "set "
+                    + USER_TOKEN_CREDENTIAL_KEY
+                    + " to match.");
+          }
+          builder.withOAuth(new StaticUserTokenProvider(userToken));
+        }
+        break;
+      default:
+        throw new UnsupportedOperationException(
+            "Auth type "
+                + authType
+                + " does not support session forwarding. Only simple and oauth2 are supported.");
     }
-    builder.withSimpleAuth(session.getUser());
 
     removeAuthSpecificKeys(clientConfig);
     builder.withClientConfig(clientConfig);
@@ -233,6 +274,7 @@ public class GravitinoAuthProvider {
     clientConfig.remove(KERBEROS_PRINCIPAL_KEY);
     clientConfig.remove(KERBEROS_KEYTAB_FILE_PATH_KEY);
     clientConfig.remove(FORWARD_SESSION_USER_KEY);
+    clientConfig.remove(USER_TOKEN_CREDENTIAL_KEY);
     clientConfig.remove(SESSION_CACHE_MAX_SIZE_KEY);
     clientConfig.remove(SESSION_CACHE_EXPIRE_AFTER_ACCESS_SECONDS_KEY);
   }
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/security/StaticUserTokenProvider.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/security/StaticUserTokenProvider.java
new file mode 100644
index 0000000000..f477a633b3
--- /dev/null
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/security/StaticUserTokenProvider.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.trino.connector.security;
+
+import com.google.common.base.Preconditions;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.client.OAuth2TokenProvider;
+
+/**
+ * An {@link OAuth2TokenProvider} that returns a pre-fetched, already-valid access token rather than
+ * minting one via client credentials. Used for per-user session forwarding: the end user's IdP
+ * access token, forwarded by Trino into the connector session, is presented directly to Gravitino
+ * so the server authorizes against the end user's identity instead of a shared service identity.
+ *
+ * <p>The raw token is returned from {@link #getAccessToken()}. The {@code Bearer } prefix is added
+ * by {@link OAuth2TokenProvider#getTokenData()}, so the token held here must not include it.
+ */
+public final class StaticUserTokenProvider extends OAuth2TokenProvider {
+
+  private final String accessToken;
+
+  /**
+   * Constructs a provider that always returns the given access token.
+   *
+   * @param accessToken the raw bearer token (without the {@code Bearer } prefix) to present to
+   *     Gravitino
+   */
+  public StaticUserTokenProvider(String accessToken) {
+    Preconditions.checkArgument(
+        StringUtils.isNotBlank(accessToken), "accessToken must not be blank");
+    this.accessToken = accessToken;
+  }
+
+  @Override
+  protected String getAccessToken() {
+    return accessToken;
+  }
+}
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorForwardUser.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorForwardUser.java
index 4380942be9..29b91f8ca3 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorForwardUser.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorForwardUser.java
@@ -18,8 +18,13 @@
  */
 package org.apache.gravitino.trino.connector;
 
+import static io.trino.spi.StandardErrorCode.GENERIC_INTERNAL_ERROR;
+import static io.trino.spi.StandardErrorCode.PERMISSION_DENIED;
 import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
 import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNotEquals;
+import static org.junit.jupiter.api.Assertions.assertNotSame;
+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.Mockito.mock;
@@ -27,12 +32,18 @@ import static org.mockito.Mockito.when;
 
 import com.google.common.collect.ImmutableMap;
 import io.trino.spi.TrinoException;
+import io.trino.spi.connector.ConnectorSession;
+import io.trino.spi.security.ConnectorIdentity;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.Function;
 import org.apache.gravitino.Catalog;
 import org.apache.gravitino.NameIdentifier;
 import org.apache.gravitino.SupportsSchemas;
+import org.apache.gravitino.client.GravitinoAdminClient;
 import org.apache.gravitino.client.GravitinoMetalake;
 import org.apache.gravitino.rel.TableCatalog;
 import org.apache.gravitino.trino.connector.catalog.CatalogConnectorContext;
+import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadata;
 import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
 import org.apache.gravitino.trino.connector.security.GravitinoAuthProvider;
 import org.junit.jupiter.api.Test;
@@ -63,15 +74,14 @@ class TestGravitinoConnectorForwardUser {
   }
 
   @Test
-  void testForwardUserWithOAuth2AuthTypeThrowsAtConstruction() {
+  void testForwardUserWithOAuth2AuthTypeSucceeds() {
     CatalogConnectorContext ctx =
         mockContextWithConfig(
             ImmutableMap.of(
                 GravitinoAuthProvider.FORWARD_SESSION_USER_KEY, "true",
                 GravitinoAuthProvider.AUTH_TYPE_KEY, "oauth2"));
 
-    TrinoException ex = assertThrows(TrinoException.class, () -> new GravitinoConnector(ctx));
-    assertEquals(GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT.toErrorCode(), ex.getErrorCode());
+    assertDoesNotThrow(() -> new GravitinoConnector(ctx));
   }
 
   @Test
@@ -91,6 +101,161 @@ class TestGravitinoConnectorForwardUser {
     assertDoesNotThrow(() -> new GravitinoConnector(ctx));
   }
 
+  @Test
+  void testSessionCacheKeyIsolatesDifferentUsers() {
+    assertNotEquals(
+        GravitinoConnector.sessionCacheKey("oauth2", "alice", "tok"),
+        GravitinoConnector.sessionCacheKey("oauth2", "bob", "tok"));
+  }
+
+  @Test
+  void testSessionCacheKeyIsolatesDifferentAuthTypes() {
+    assertNotEquals(
+        GravitinoConnector.sessionCacheKey("oauth2", "alice", "tok"),
+        GravitinoConnector.sessionCacheKey("simple", "alice", "tok"));
+  }
+
+  @Test
+  void testSessionCacheKeyIsolatesDifferentTokens() {
+    assertNotEquals(
+        GravitinoConnector.sessionCacheKey("oauth2", "alice", "token-a"),
+        GravitinoConnector.sessionCacheKey("oauth2", "alice", "token-b"));
+  }
+
+  @Test
+  void testSessionCacheKeyIsStableForSameUserAuthTypeAndToken() {
+    assertEquals(
+        GravitinoConnector.sessionCacheKey("oauth2", "alice", "tok"),
+        GravitinoConnector.sessionCacheKey("oauth2", "alice", "tok"));
+  }
+
+  @Test
+  void testSessionCacheKeyIgnoresBlankTokenForSimpleAuth() {
+    assertEquals(
+        GravitinoConnector.sessionCacheKey("simple", "alice", null),
+        GravitinoConnector.sessionCacheKey("simple", "alice", ""));
+  }
+
+  @Test
+  void testResolveSessionMetadataBuildsNewClientOnTokenRotation() {
+    CatalogConnectorContext ctx =
+        mockContextWithConfig(
+            ImmutableMap.of(
+                GravitinoAuthProvider.FORWARD_SESSION_USER_KEY, "true",
+                GravitinoAuthProvider.AUTH_TYPE_KEY, "oauth2"));
+    AtomicInteger buildCount = new AtomicInteger();
+    GravitinoConnector connector =
+        newConnectorWithAuthClient(ctx, session -> mockAdminClient(ctx.getMetalake(), buildCount));
+
+    CatalogConnectorMetadata first =
+        connector.resolveSessionMetadata(mockSession("alice", "token-a"));
+    CatalogConnectorMetadata second =
+        connector.resolveSessionMetadata(mockSession("alice", "token-a"));
+    CatalogConnectorMetadata third =
+        connector.resolveSessionMetadata(mockSession("alice", "token-b"));
+
+    assertSame(first, second, "same user/token should reuse the cached client");
+    assertNotSame(first, third, "a rotated token must not reuse the stale cached client");
+    assertEquals(2, buildCount.get(), "a rotated token must trigger a fresh client build");
+  }
+
+  @Test
+  void testResolveSessionMetadataMapsAuthSpecificFailureToPermissionDenied() {
+    CatalogConnectorContext ctx =
+        mockContextWithConfig(
+            ImmutableMap.of(
+                GravitinoAuthProvider.FORWARD_SESSION_USER_KEY, "true",
+                GravitinoAuthProvider.AUTH_TYPE_KEY, "oauth2"));
+    GravitinoConnector connector =
+        newConnectorWithAuthClient(
+            ctx,
+            session -> {
+              throw new IllegalArgumentException("No forwarded user token found");
+            });
+
+    TrinoException ex =
+        assertThrows(
+            TrinoException.class,
+            () -> connector.resolveSessionMetadata(mockSession("alice", "token-a")));
+    assertEquals(PERMISSION_DENIED.toErrorCode(), ex.getErrorCode());
+  }
+
+  @Test
+  void testResolveSessionMetadataPreservesTrinoExceptionErrorCode() {
+    CatalogConnectorContext ctx =
+        mockContextWithConfig(
+            ImmutableMap.of(
+                GravitinoAuthProvider.FORWARD_SESSION_USER_KEY, "true",
+                GravitinoAuthProvider.AUTH_TYPE_KEY, "oauth2"));
+    GravitinoConnector connector =
+        newConnectorWithAuthClient(
+            ctx,
+            session -> {
+              throw new TrinoException(
+                  GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT, "No forwarded user token found");
+            });
+
+    TrinoException ex =
+        assertThrows(
+            TrinoException.class,
+            () -> connector.resolveSessionMetadata(mockSession("alice", "token-a")));
+    assertEquals(GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT.toErrorCode(), ex.getErrorCode());
+  }
+
+  @Test
+  void testResolveSessionMetadataMapsUnexpectedFailureToGenericInternalError() {
+    CatalogConnectorContext ctx =
+        mockContextWithConfig(
+            ImmutableMap.of(
+                GravitinoAuthProvider.FORWARD_SESSION_USER_KEY, "true",
+                GravitinoAuthProvider.AUTH_TYPE_KEY, "oauth2"));
+    GravitinoConnector connector =
+        newConnectorWithAuthClient(
+            ctx,
+            session -> {
+              throw new RuntimeException("connection refused");
+            });
+
+    TrinoException ex =
+        assertThrows(
+            TrinoException.class,
+            () -> connector.resolveSessionMetadata(mockSession("alice", "token-a")));
+    assertEquals(GENERIC_INTERNAL_ERROR.toErrorCode(), ex.getErrorCode());
+  }
+
+  /**
+   * Creates a {@link GravitinoConnector} whose {@code buildAuthClient} is overridden with the given
+   * function, so tests can control what building the per-user client does without mocking the
+   * static {@link GravitinoAuthProvider#buildForSession}.
+   */
+  private static GravitinoConnector newConnectorWithAuthClient(
+      CatalogConnectorContext ctx,
+      Function<ConnectorSession, GravitinoAdminClient> authClientBuilder) {
+    return new GravitinoConnector(ctx) {
+      @Override
+      GravitinoAdminClient buildAuthClient(ConnectorSession session) {
+        return authClientBuilder.apply(session);
+      }
+    };
+  }
+
+  private static GravitinoAdminClient mockAdminClient(
+      GravitinoMetalake metalake, AtomicInteger buildCount) {
+    buildCount.incrementAndGet();
+    GravitinoAdminClient client = mock(GravitinoAdminClient.class);
+    when(client.loadMetalake(any())).thenReturn(metalake);
+    return client;
+  }
+
+  private static ConnectorSession mockSession(String user, String token) {
+    ConnectorIdentity identity = mock(ConnectorIdentity.class);
+    when(identity.getExtraCredentials()).thenReturn(ImmutableMap.of("token", token));
+    ConnectorSession session = mock(ConnectorSession.class);
+    when(session.getUser()).thenReturn(user);
+    when(session.getIdentity()).thenReturn(identity);
+    return session;
+  }
+
   private static CatalogConnectorContext mockContextWithConfig(
       ImmutableMap<String, String> extraConfig) {
     GravitinoCatalog mockCatalog = mock(GravitinoCatalog.class);
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
index e2c7c55255..e16afd8e6f 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
@@ -57,6 +57,33 @@ public class TestIcebergCatalogPropertyConverter {
         "Missing required property for Hive backend: [uri]");
   }
 
+  @Test
+  public void testRestBackendProperty() {
+    PropertyConverter propertyConverter = new IcebergCatalogPropertyConverter();
+    Map<String, String> gravitinoIcebergConfig =
+        ImmutableMap.<String, String>builder()
+            .put("uri", "http://localhost:9001/iceberg")
+            .put("catalog-backend", "rest")
+            .put("warehouse", "gt_iceberg_rest")
+            .build();
+    Map<String, String> restBackendConfig =
+        propertyConverter.gravitinoToEngineProperties(gravitinoIcebergConfig);
+
+    Assertions.assertEquals(restBackendConfig.get("iceberg.catalog.type"), "rest");
+    Assertions.assertEquals(
+        restBackendConfig.get("iceberg.rest-catalog.uri"), "http://localhost:9001/iceberg");
+    Assertions.assertEquals(
+        restBackendConfig.get("iceberg.rest-catalog.warehouse"), "gt_iceberg_rest");
+
+    Map<String, String> wrongMap = Maps.newHashMap(gravitinoIcebergConfig);
+    wrongMap.remove("uri");
+
+    Assertions.assertThrows(
+        TrinoException.class,
+        () -> propertyConverter.gravitinoToEngineProperties(wrongMap),
+        "Missing required property for Rest backend: [uri]");
+  }
+
   @Test
   public void testJDBCBackendProperty() {
     PropertyConverter propertyConverter = new IcebergCatalogPropertyConverter();
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/security/TestGravitinoAuthProvider.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/security/TestGravitinoAuthProvider.java
index 131eee6af2..03ede70a6a 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/security/TestGravitinoAuthProvider.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/security/TestGravitinoAuthProvider.java
@@ -25,7 +25,9 @@ import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.when;
 
 import com.google.common.collect.ImmutableMap;
+import io.trino.spi.TrinoException;
 import io.trino.spi.connector.ConnectorSession;
+import io.trino.spi.security.ConnectorIdentity;
 import java.io.File;
 import java.io.IOException;
 import java.nio.file.Files;
@@ -259,6 +261,63 @@ public class TestGravitinoAuthProvider {
         () -> GravitinoAuthProvider.buildForSession(config, session));
   }
 
+  @Test
+  public void testBuildForSessionOAuth2() {
+    GravitinoConfig config =
+        buildConfig(
+            ImmutableMap.of(
+                GravitinoAuthProvider.AUTH_TYPE_KEY, "oauth2",
+                GravitinoAuthProvider.FORWARD_SESSION_USER_KEY, "true"));
+
+    ConnectorSession session = mock(ConnectorSession.class);
+    when(session.getUser()).thenReturn("alice");
+    when(session.getIdentity())
+        .thenReturn(
+            ConnectorIdentity.forUser("alice")
+                .withExtraCredentials(ImmutableMap.of("token", "forwarded-user-jwt"))
+                .build());
+
+    GravitinoAdminClient client = GravitinoAuthProvider.buildForSession(config, session);
+    assertNotNull(client);
+  }
+
+  @Test
+  public void testBuildForSessionOAuth2WithCustomCredentialKey() {
+    GravitinoConfig config =
+        buildConfig(
+            ImmutableMap.of(
+                GravitinoAuthProvider.AUTH_TYPE_KEY, "oauth2",
+                GravitinoAuthProvider.FORWARD_SESSION_USER_KEY, "true",
+                GravitinoAuthProvider.USER_TOKEN_CREDENTIAL_KEY, "access_token"));
+
+    ConnectorSession session = mock(ConnectorSession.class);
+    when(session.getUser()).thenReturn("alice");
+    when(session.getIdentity())
+        .thenReturn(
+            ConnectorIdentity.forUser("alice")
+                .withExtraCredentials(ImmutableMap.of("access_token", "alice-jwt"))
+                .build());
+
+    GravitinoAdminClient client = GravitinoAuthProvider.buildForSession(config, session);
+    assertNotNull(client);
+  }
+
+  @Test
+  public void testBuildForSessionOAuth2ThrowsWhenTokenMissing() {
+    GravitinoConfig config =
+        buildConfig(
+            ImmutableMap.of(
+                GravitinoAuthProvider.AUTH_TYPE_KEY, "oauth2",
+                GravitinoAuthProvider.FORWARD_SESSION_USER_KEY, "true"));
+
+    ConnectorSession session = mock(ConnectorSession.class);
+    when(session.getUser()).thenReturn("alice");
+    when(session.getIdentity()).thenReturn(ConnectorIdentity.forUser("alice").build());
+
+    assertThrows(
+        TrinoException.class, () -> GravitinoAuthProvider.buildForSession(config, session));
+  }
+
   private GravitinoConfig buildConfig(ImmutableMap<String, String> authConfig) {
     ImmutableMap.Builder<String, String> builder =
         ImmutableMap.<String, String>builder()


(gravitino) 08/13: [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Discover the Iceberg REST server instead of a manual switch

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diqiu50 pushed a commit to branch trino-irc-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit 320489684ee048076101c49510e285b500e51013
Author: diqiu50 <di...@apache.org>
AuthorDate: Mon Aug 24 15:26:50 2026 +0800

    [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Discover the Iceberg REST server instead of a manual switch
    
    Replace gravitino.iceberg.rest-enabled with automatic discovery. The
    Trino connector already connects to the Gravitino server to load
    metalakes, so it now also asks that server whether it has an Iceberg
    REST server running for the connector's metalake, and routes
    lakehouse-iceberg catalogs through the reported endpoint. When the
    server reports nothing — the Iceberg REST server is not running, or
    serves a different metalake — catalogs fall back to translating
    catalog-backend as before, with no configuration required either way.
    
    Server side: AuxiliaryServiceManager gains a query method for whether
    an auxiliary service is registered, and a new GET /api/system/iceberg-rest
    endpoint reports the Iceberg REST server's address for a given
    metalake, falling back to the request's own host when the service
    binds to a wildcard address. The client gains a matching method
    following the existing REST client patterns.
    
    gravitino.iceberg.rest-uri remains as a manual override for topologies
    where the discovered address is not reachable. The discovery call is
    piggybacked on the existing periodic metalake poll, so it adds no new
    network schedule, and failures (including talking to a Gravitino
    server older than this endpoint) are swallowed rather than
    interrupting catalog loading.
    
    This also resolves the multi-metalake ambiguity in the previous
    design: the server only reports an endpoint for the metalake it is
    configured to serve, so a same-named catalog in a different metalake
    can no longer be silently misrouted.
    
    (cherry picked from commit a8015c9e3fc860bf0059adce70244646ea869492)
---
 .../gravitino/client/GravitinoClientBase.java      |  23 ++++
 .../dto/responses/IcebergRESTServiceResponse.java  |  56 ++++++++
 .../java/org/apache/gravitino/GravitinoEnv.java    |   9 ++
 .../auxiliary/AuxiliaryServiceManager.java         |  10 ++
 docs/trino-connector/authentication.md             |   3 +-
 docs/trino-connector/catalog-iceberg.md            |  28 ++--
 docs/trino-connector/configuration.md              |  13 +-
 .../docker-script/docker-compose.yaml              |   2 -
 .../init/trino/config/catalog/gravitino.properties |   1 -
 .../docker-script/init/trino/init.sh               |   4 -
 .../integration/test/container/ContainerSuite.java |  23 +---
 .../test/container/TrinoITContainers.java          |  10 +-
 .../gravitino/integration/test/util/BaseIT.java    |  11 --
 .../web/rest/IcebergRESTServiceOperations.java     | 105 +++++++++++++++
 .../integration/test/TrinoConnectorIT.java         |   1 -
 .../integration/test/TrinoQueryITBase.java         |   1 -
 .../gravitino/trino/connector/GravitinoConfig.java |  84 +++++-------
 .../connector/catalog/CatalogConnectorManager.java |  18 +++
 .../iceberg/IcebergCatalogPropertyConverter.java   |  28 ++--
 .../catalog/iceberg/IcebergConnectorAdapter.java   |  11 +-
 .../trino/connector/TestGravitinoConfig.java       |  55 +++++---
 .../TestIcebergCatalogPropertyConverter.java       | 148 ++++++++++++++++-----
 22 files changed, 453 insertions(+), 191 deletions(-)

diff --git a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClientBase.java b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClientBase.java
index 996c149591..07c7e9cca6 100644
--- a/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClientBase.java
+++ b/clients/client-java/src/main/java/org/apache/gravitino/client/GravitinoClientBase.java
@@ -29,10 +29,12 @@ import java.net.URI;
 import java.net.URISyntaxException;
 import java.util.Collections;
 import java.util.Map;
+import java.util.Optional;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.gravitino.NameIdentifier;
 import org.apache.gravitino.Namespace;
 import org.apache.gravitino.Version;
+import org.apache.gravitino.dto.responses.IcebergRESTServiceResponse;
 import org.apache.gravitino.dto.responses.MetalakeResponse;
 import org.apache.gravitino.dto.responses.VersionResponse;
 import org.apache.gravitino.exceptions.GravitinoRuntimeException;
@@ -185,6 +187,27 @@ public abstract class GravitinoClientBase implements Closeable {
     return new GravitinoVersion(resp.getVersion());
   }
 
+  /**
+   * Retrieves the endpoint of the Gravitino Iceberg REST server, if it is running and serves the
+   * given metalake.
+   *
+   * @param metalakeName the metalake the caller intends to route through the Iceberg REST server
+   * @return the Iceberg REST server endpoint, or empty if it is not running or serves a different
+   *     metalake
+   */
+  public Optional<String> icebergRestServiceUri(String metalakeName) {
+    IcebergRESTServiceResponse resp =
+        restClient.get(
+            "api/system/iceberg-rest",
+            ImmutableMap.of("metalake", metalakeName),
+            IcebergRESTServiceResponse.class,
+            Collections.emptyMap(),
+            ErrorHandlers.restErrorHandler());
+    resp.validate();
+
+    return Optional.ofNullable(resp.getUri());
+  }
+
   /** Closes the GravitinoClient and releases any underlying resources. */
   @Override
   public void close() {
diff --git a/common/src/main/java/org/apache/gravitino/dto/responses/IcebergRESTServiceResponse.java b/common/src/main/java/org/apache/gravitino/dto/responses/IcebergRESTServiceResponse.java
new file mode 100644
index 0000000000..89c071dfcc
--- /dev/null
+++ b/common/src/main/java/org/apache/gravitino/dto/responses/IcebergRESTServiceResponse.java
@@ -0,0 +1,56 @@
+/*
+ * 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.dto.responses;
+
+import com.fasterxml.jackson.annotation.JsonProperty;
+import javax.annotation.Nullable;
+import lombok.EqualsAndHashCode;
+import lombok.Getter;
+import lombok.ToString;
+
+/**
+ * Represents a response reporting the endpoint of the Gravitino Iceberg REST server, if it is
+ * running and serves the requested metalake.
+ */
+@Getter
+@EqualsAndHashCode(callSuper = true)
+@ToString
+public class IcebergRESTServiceResponse extends BaseResponse {
+
+  @Nullable
+  @JsonProperty("uri")
+  private final String uri;
+
+  /**
+   * Constructor for IcebergRESTServiceResponse.
+   *
+   * @param uri the Iceberg REST server endpoint, or {@code null} when it is not running or does not
+   *     serve the requested metalake
+   */
+  public IcebergRESTServiceResponse(@Nullable String uri) {
+    super(0);
+    this.uri = uri;
+  }
+
+  /** Default constructor for IcebergRESTServiceResponse. (Used for Jackson deserialization.) */
+  public IcebergRESTServiceResponse() {
+    super();
+    this.uri = null;
+  }
+}
diff --git a/core/src/main/java/org/apache/gravitino/GravitinoEnv.java b/core/src/main/java/org/apache/gravitino/GravitinoEnv.java
index 4f42989045..fc69a7cbde 100644
--- a/core/src/main/java/org/apache/gravitino/GravitinoEnv.java
+++ b/core/src/main/java/org/apache/gravitino/GravitinoEnv.java
@@ -235,6 +235,15 @@ public class GravitinoEnv {
     return config;
   }
 
+  /**
+   * Get the auxiliary service manager associated with the Gravitino environment.
+   *
+   * @return The auxiliary service manager instance.
+   */
+  public AuxiliaryServiceManager auxServiceManager() {
+    return auxServiceManager;
+  }
+
   /**
    * Get the EntityStore associated with the Gravitino environment.
    *
diff --git a/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java b/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java
index 08444abb3f..accb23f799 100644
--- a/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java
+++ b/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java
@@ -95,6 +95,16 @@ public class AuxiliaryServiceManager {
   }
 
   @VisibleForTesting
+  /**
+   * Returns whether the given auxiliary service was configured and registered.
+   *
+   * @param auxServiceName the auxiliary service's short name, e.g. {@code iceberg-rest}
+   * @return true if the service is registered
+   */
+  public boolean isAuxServiceRegistered(String auxServiceName) {
+    return auxServices.containsKey(auxServiceName);
+  }
+
   public IsolatedClassLoader getIsolatedClassLoader(List<String> classPaths) {
     return IsolatedClassLoader.buildClassLoader(classPaths);
   }
diff --git a/docs/trino-connector/authentication.md b/docs/trino-connector/authentication.md
index 322eef9f5d..42c7932f6b 100644
--- a/docs/trino-connector/authentication.md
+++ b/docs/trino-connector/authentication.md
@@ -194,13 +194,12 @@ Whether the coordinator can populate this extra-credential depends on the Trino
 The `gravitino.client.oauth2.*` properties above still configure the shared bootstrap/admin client used for catalog discovery — they are unrelated to the per-user forwarded token.
 
 For an Iceberg catalog reached through the Gravitino Iceberg REST server (IRC) — every
-`lakehouse-iceberg` catalog, unless `gravitino.iceberg.rest-enabled=false`; see [Iceberg
+`lakehouse-iceberg` catalog for which the Gravitino server reports a running IRC; see [Iceberg
 catalog](./catalog-iceberg.md#how-trino-reaches-the-catalog) — the IRC's own authentication is
 configured once per Trino cluster with the `gravitino.iceberg.rest-catalog.` prefix, and
 `iceberg.rest-catalog.session=USER` is set automatically when `forwardUser=true`:
 
 ```properties
-gravitino.iceberg.rest-uri=http://gravitino-host:9001/iceberg
 gravitino.iceberg.rest-catalog.security=OAUTH2
 gravitino.iceberg.rest-catalog.oauth2.credential=service-account-id:service-account-secret
 gravitino.iceberg.rest-catalog.oauth2.server-uri=http://your-idp/realms/gravitino/protocol/openid-connect/token
diff --git a/docs/trino-connector/catalog-iceberg.md b/docs/trino-connector/catalog-iceberg.md
index dd00d8cab1..02779e8041 100644
--- a/docs/trino-connector/catalog-iceberg.md
+++ b/docs/trino-connector/catalog-iceberg.md
@@ -33,7 +33,17 @@ nowhere to put the session token of an STS temporary credential — so a catalog
 IRC means every table access gets a freshly issued temporary credential over the Iceberg REST
 protocol.
 
-Configure the IRC endpoint once per Trino cluster, in `etc/catalog/gravitino.properties`:
+The connector already connects to the Gravitino server (it is how catalogs are discovered in the
+first place), so it also asks that server whether it has an Iceberg REST server running for the
+connector's metalake, and uses the endpoint the server reports. Nothing needs to be configured for
+this: `etc/catalog/gravitino.properties` only needs the usual `gravitino.uri` and
+`gravitino.metalake`. If the server reports no endpoint — the IRC is not running, or it serves a
+different metalake — `lakehouse-iceberg` catalogs fall back to translating `catalog-backend` as
+before, and credential vending does not work.
+
+Set `gravitino.iceberg.rest-uri` only to override the discovered endpoint, for example when the IRC
+is not reachable at the address the Gravitino server itself reports (a split network, or the IRC
+deployed independently of the main server):
 
 ```properties
 connector.name=gravitino
@@ -43,10 +53,6 @@ gravitino.uri=http://gravitino-host:8090
 gravitino.iceberg.rest-uri=http://gravitino-host:9001/iceberg
 ```
 
-The endpoint is deployment topology, not a property of the data source, so it does not belong on the
-catalog: it would have to be repeated on every new catalog, moving the IRC would mean editing all of
-them, and one catalog could not serve two Trino clusters that reach the IRC by different hostnames.
-
 The connector derives everything else from the catalog itself. The Gravitino catalog name is passed
 as both `iceberg.rest-catalog.warehouse` and `iceberg.rest-catalog.prefix` — the Iceberg client
 selects the catalog twice over, first as the query parameter of the `GET /v1/config` call that
@@ -106,14 +112,14 @@ keeping per-user credential vending and per-user authorization intact. Set
 ### Limitations
 
 - One IRC serves exactly one metalake, fixed at startup by
-  `gravitino.iceberg-rest.gravitino-metalake`. In multi-metalake mode
-  (`gravitino.use-single-metalake=false`), only catalogs in that metalake are reachable; the others
-  fail on the IRC side with `NoSuchCatalogException`.
+  `gravitino.iceberg-rest.gravitino-metalake`. The Gravitino server only reports the IRC's endpoint
+  for that metalake; in multi-metalake mode (`gravitino.use-single-metalake=false`), catalogs in any
+  other metalake fall back to translating `catalog-backend` instead of failing outright.
 - A catalog created with `catalog-backend=rest` keeps pointing at its own configured `uri` and is
   not re-routed, since it already reaches an Iceberg REST catalog directly.
-- To disable this routing entirely — for a deployment that does not run the IRC — set
-  `gravitino.iceberg.rest-enabled=false`. Iceberg catalogs are then translated into Trino's `jdbc`
-  or `hive_metastore` catalog types as before, and credential vending does not work.
+- A deployment that does not run the IRC needs no configuration at all: the server reports no
+  endpoint, and `lakehouse-iceberg` catalogs are translated into Trino's `jdbc` or `hive_metastore`
+  catalog types as before.
 
 ## Schema Operations
 
diff --git a/docs/trino-connector/configuration.md b/docs/trino-connector/configuration.md
index 6d225a6cec..9e6747ef67 100644
--- a/docs/trino-connector/configuration.md
+++ b/docs/trino-connector/configuration.md
@@ -29,21 +29,16 @@ license: "This software is licensed under the Apache License version 2."
 | gravitino.client.                           | string  | (none)                | The configuration key prefix for the Gravitino client config.                                                                                                                                                                                                                                                                                    | No       |
 | gravitino.trino.skip-catalog-patterns       | string  | (none)                | The `gravitino.trino.skip-catalog-patterns` defines a comma-separated list of catalog name regex patterns that should be excluded from loading. For example, `test_.*, .*_tmp` excludes all catalogs starting with `test_` or ending with `_tmp`.                                                                                                | No       |
 | gravitino.use-single-metalake               | boolean | true                  | If `true`, only one metalake is used and catalogs are identified by `<catalog_name>`. If `false`, multi-metalake mode is enabled and catalogs are identified by `<metalake_name>.<catalog_name>`.                                                                                                                                                | No       |
-| gravitino.iceberg.rest-enabled              | boolean | true                  | If `true`, `lakehouse-iceberg` catalogs are loaded through the Gravitino Iceberg REST server (IRC) instead of being translated into Trino's `jdbc` or `hive_metastore` Iceberg catalog type. This is what makes credential vending work. Requires `gravitino.iceberg.rest-uri`. Set to `false` for a deployment that does not run the IRC.                                    | No       |
-| gravitino.iceberg.rest-uri                  | string  | (none)                | The endpoint of the Gravitino Iceberg REST server, for example `http://gravitino-host:9001/iceberg`. Required when `gravitino.iceberg.rest-enabled` is `true` and the metalake contains `lakehouse-iceberg` catalogs whose `catalog-backend` is not `rest`.                                                          | No       |
+| gravitino.iceberg.rest-uri                  | string  | (none)                | The endpoint of the Gravitino Iceberg REST server (IRC). Discovered automatically from the Gravitino server, which is asked whether it has an IRC running for this connector's metalake; set this only to override the discovered value. When an endpoint is available (discovered or configured), `lakehouse-iceberg` catalogs whose `catalog-backend` is not `rest` are loaded through it instead of being translated in [...]
 | gravitino.iceberg.rest-catalog.             | string  | (none)                | The configuration key prefix for properties passed through to the internal Trino Iceberg REST catalog. The prefix is rewritten to `iceberg.rest-catalog.`, so `gravitino.iceberg.rest-catalog.security=OAUTH2` becomes `iceberg.rest-catalog.security=OAUTH2`. The `uri`, `warehouse` and `prefix` keys are reserved and always derived by the connector.                     | No       |
 
 To configure the Gravitino client, use properties prefixed with `gravitino.client.`. These properties will directly passed to the Gravitino client.
 
 **Note:** Invalid configuration properties will result in exceptions. Please see [Gravitino Java client configurations](../how-to-use-gravitino-client.md#java-client-configuration) for more support client configuration.
 
-:::caution
-`gravitino.iceberg.rest-enabled` defaults to `true`. When upgrading an existing deployment whose
-metalake contains `lakehouse-iceberg` catalogs with `catalog-backend=jdbc` or `hive`, those catalogs
-fail to load unless you either set `gravitino.iceberg.rest-uri` to your Iceberg REST server endpoint,
-or set `gravitino.iceberg.rest-enabled=false` to keep the previous behavior. See
-[Iceberg catalog](./catalog-iceberg.md#how-trino-reaches-the-catalog).
-:::
+Upgrading an existing deployment needs no action: a Gravitino server without the Iceberg REST server
+running reports no endpoint, so `lakehouse-iceberg` catalogs keep translating `catalog-backend` as
+before. See [Iceberg catalog](./catalog-iceberg.md#how-trino-reaches-the-catalog).
 
 Multi-metalake mode (`gravitino.use-single-metalake=false`) is supported on Trino connector versions 440-445 and 469-478. On versions 446-468, a warning is logged and the connector initializes, but the mode is not fully supported and some operations may fail.
 
diff --git a/integration-test-common/docker-script/docker-compose.yaml b/integration-test-common/docker-script/docker-compose.yaml
index 1dfb8f5a7d..3ed57d07ca 100644
--- a/integration-test-common/docker-script/docker-compose.yaml
+++ b/integration-test-common/docker-script/docker-compose.yaml
@@ -87,7 +87,6 @@ services:
       - HADOOP_USER_NAME=anonymous
       - GRAVITINO_HOST_IP=host.docker.internal
       - GRAVITINO_HOST_PORT=${GRAVITINO_SERVER_PORT:-8090}
-      - GRAVITINO_ICEBERG_REST_PORT=${GRAVITINO_ICEBERG_REST_PORT:-9001}
       - GRAVITINO_METALAKE_NAME=test
       - HIVE_HOST_IP=hive
       - TRINO_WORKER_NUM=${TRINO_WORKER_NUM:-0}
@@ -123,7 +122,6 @@ services:
       - HADOOP_USER_NAME=anonymous
       - GRAVITINO_HOST_IP=host.docker.internal
       - GRAVITINO_HOST_PORT=${GRAVITINO_SERVER_PORT:-8090}
-      - GRAVITINO_ICEBERG_REST_PORT=${GRAVITINO_ICEBERG_REST_PORT:-9001}
       - GRAVITINO_METALAKE_NAME=test
       - HIVE_HOST_IP=hive
       - TRINO_ROLE=worker
diff --git a/integration-test-common/docker-script/init/trino/config/catalog/gravitino.properties b/integration-test-common/docker-script/init/trino/config/catalog/gravitino.properties
index d38c18c458..08789c84c0 100644
--- a/integration-test-common/docker-script/init/trino/config/catalog/gravitino.properties
+++ b/integration-test-common/docker-script/init/trino/config/catalog/gravitino.properties
@@ -20,7 +20,6 @@
 connector.name = gravitino
 gravitino.uri = http://GRAVITINO_HOST_IP:GRAVITINO_HOST_PORT
 gravitino.metalake = GRAVITINO_METALAKE_NAME
-gravitino.iceberg.rest-uri = http://GRAVITINO_ICEBERG_REST_HOST:GRAVITINO_ICEBERG_REST_PORT/iceberg
 gravitino.trino.skip-version-validation=true
 gravitino.client.authType = simple
 gravitino.client.session.forwardUser = true
diff --git a/integration-test-common/docker-script/init/trino/init.sh b/integration-test-common/docker-script/init/trino/init.sh
index a65ec5ab90..077c6f77d0 100644
--- a/integration-test-common/docker-script/init/trino/init.sh
+++ b/integration-test-common/docker-script/init/trino/init.sh
@@ -34,10 +34,6 @@ cp /usr/lib/trino/plugin/mysql/*mysql-connector-j-*.jar /usr/lib/trino/plugin/ic
 sed -i "s/GRAVITINO_HOST_IP:GRAVITINO_HOST_PORT/${GRAVITINO_HOST_IP}:${GRAVITINO_HOST_PORT}/g" /etc/trino/catalog/gravitino.properties
 # Update `gravitino.metalake = GRAVITINO_METALAKE_NAME` in the `conf/catalog/gravitino.properties`
 sed -i "s/GRAVITINO_METALAKE_NAME/${GRAVITINO_METALAKE_NAME}/g" /etc/trino/catalog/gravitino.properties
-# Update `gravitino.iceberg.rest-uri` in the `conf/catalog/gravitino.properties`. The Iceberg REST
-# server runs on the same host as the Gravitino server but on a different port, so it needs its own
-# placeholder pair — reusing GRAVITINO_HOST_IP:GRAVITINO_HOST_PORT would substitute the server port.
-sed -i "s/GRAVITINO_ICEBERG_REST_HOST:GRAVITINO_ICEBERG_REST_PORT/${GRAVITINO_HOST_IP}:${GRAVITINO_ICEBERG_REST_PORT}/g" /etc/trino/catalog/gravitino.properties
 # Update `node.id=NODE_ID` in the `/conf/node.properties`
 sed -i "s/NODE_ID/${RANDOM}-${RANDOM}-${RANDOM}-${RANDOM}-${RANDOM}/g" /etc/trino/node.properties
 
diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.java
index ad35692dbb..b2b0ae50da 100644
--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.java
+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.java
@@ -288,7 +288,6 @@ public class ContainerSuite implements Closeable {
       String trinoConfDir,
       String trinoConnectorLibDir,
       int gravitinoServerPort,
-      int icebergRestServerPort,
       String metalakeName) {
     ITUtils.cleanDisk();
     if (trinoContainer == null) {
@@ -297,23 +296,15 @@ public class ContainerSuite implements Closeable {
           initIfNecessary();
           // Start Trino container
           String hiveContainerIp = hiveContainer.getContainerIpAddress();
-          ImmutableMap.Builder<String, String> envVars =
-              ImmutableMap.<String, String>builder()
-                  .put("HADOOP_USER_NAME", "anonymous")
-                  .put("GRAVITINO_HOST_IP", "host.docker.internal")
-                  .put("GRAVITINO_HOST_PORT", String.valueOf(gravitinoServerPort))
-                  .put("GRAVITINO_METALAKE_NAME", metalakeName);
-          if (icebergRestServerPort > 0) {
-            envVars.put("GRAVITINO_ICEBERG_REST_PORT", String.valueOf(icebergRestServerPort));
-          } else {
-            LOG.info(
-                "No Iceberg REST server port supplied; Trino falls back to the compose default. "
-                    + "Catalogs routed through the Iceberg REST server will not work in this "
-                    + "container.");
-          }
           TrinoContainer.Builder trinoBuilder =
               TrinoContainer.builder()
-                  .withEnvVars(envVars.build())
+                  .withEnvVars(
+                      ImmutableMap.<String, String>builder()
+                          .put("HADOOP_USER_NAME", "anonymous")
+                          .put("GRAVITINO_HOST_IP", "host.docker.internal")
+                          .put("GRAVITINO_HOST_PORT", String.valueOf(gravitinoServerPort))
+                          .put("GRAVITINO_METALAKE_NAME", metalakeName)
+                          .build())
                   .withNetwork(getNetwork())
                   .withExtraHosts(
                       ImmutableMap.<String, String>builder()
diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/TrinoITContainers.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/TrinoITContainers.java
index 572b948d55..a02e12de6a 100644
--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/TrinoITContainers.java
+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/TrinoITContainers.java
@@ -50,12 +50,11 @@ public class TrinoITContainers implements AutoCloseable {
   }
 
   public void launch(int gravitinoServerPort) throws Exception {
-    launch(gravitinoServerPort, 0, "hive2", false, null, null, null);
+    launch(gravitinoServerPort, "hive2", false, null, null, null);
   }
 
   public void launch(
       int gravitinoServerPort,
-      int icebergRestServerPort,
       String hiveRuntimeVersion,
       boolean isTrinoConnectorTest,
       Integer trinoWorkerNum,
@@ -82,13 +81,6 @@ public class TrinoITContainers implements AutoCloseable {
     }
     env.put("GRAVITINO_SERVER_PORT", String.valueOf(gravitinoServerPort));
     env.put("HIVE_RUNTIME_VERSION", hiveRuntimeVersion);
-    if (icebergRestServerPort > 0) {
-      env.put("GRAVITINO_ICEBERG_REST_PORT", String.valueOf(icebergRestServerPort));
-    } else {
-      LOG.info(
-          "No Iceberg REST server port supplied; Trino falls back to the compose default. "
-              + "Catalogs routed through the Iceberg REST server will not work in this container.");
-    }
     env.put("TRINO_CONNECTOR_TEST", String.valueOf(isTrinoConnectorTest));
     if (System.getProperty("gravitino.log.path") != null) {
       env.put("GRAVITINO_LOG_PATH", System.getProperty("gravitino.log.path"));
diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java
index 0c247a22f1..ef45535de9 100644
--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java
+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java
@@ -30,7 +30,6 @@ import com.google.common.collect.ImmutableMap;
 import java.io.File;
 import java.io.IOException;
 import java.lang.reflect.Field;
-import java.net.URI;
 import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
@@ -687,16 +686,6 @@ public class BaseIT {
     this.customConfigs.putAll(icebergRestConfigs);
   }
 
-  /**
-   * Returns the port the Iceberg REST auxiliary service listens on. Only valid once {@link
-   * #startIntegrationTest()} has run, since it reads the started server's config.
-   *
-   * @return the Iceberg REST service port
-   */
-  public int getIcebergRestServicePort() {
-    return URI.create(getIcebergRestServiceUri()).getPort();
-  }
-
   protected String getIcebergRestServiceUri() {
     JettyServerConfig jettyServerConfig =
         JettyServerConfig.fromConfig(serverConfig, String.format("gravitino.iceberg-rest."));
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java
new file mode 100644
index 0000000000..0ea698a6a4
--- /dev/null
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java
@@ -0,0 +1,105 @@
+/*
+ * 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.web.rest;
+
+import com.codahale.metrics.annotation.ResponseMetered;
+import com.codahale.metrics.annotation.Timed;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
+import javax.ws.rs.GET;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.dto.responses.IcebergRESTServiceResponse;
+import org.apache.gravitino.metrics.MetricNames;
+import org.apache.gravitino.server.web.JettyServerConfig;
+import org.apache.gravitino.server.web.Utils;
+
+/**
+ * Reports the endpoint of the Gravitino Iceberg REST server, so that clients which already connect
+ * to this Gravitino server can discover it instead of requiring it to be configured separately.
+ */
+@Path("/system/iceberg-rest")
+@Consumes(MediaType.APPLICATION_JSON)
+@Produces(MediaType.APPLICATION_JSON)
+public class IcebergRESTServiceOperations {
+
+  // Matches gravitino.auxService.names / AuxiliaryServiceManager's registration key.
+  private static final String AUX_SERVICE_NAME = "iceberg-rest";
+  private static final String CONFIG_PREFIX = "gravitino.iceberg-rest.";
+  // The post-strip key used by the Iceberg REST server itself; see
+  // IcebergConstants.GRAVITINO_METALAKE and DynamicIcebergConfigProvider.
+  private static final String SERVED_METALAKE_KEY = CONFIG_PREFIX + "gravitino-metalake";
+
+  @Context private HttpServletRequest httpRequest;
+
+  /**
+   * Reports the Iceberg REST server's endpoint for the requested metalake.
+   *
+   * @param metalake the metalake the caller intends to route through the Iceberg REST server; may
+   *     be blank, in which case the endpoint is reported regardless of which metalake it serves
+   * @return a response whose {@code uri} is {@code null} when the Iceberg REST server is not
+   *     running, or does not serve the requested metalake
+   */
+  @GET
+  @Timed(name = "iceberg-rest-service." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
+  @ResponseMetered(name = "iceberg-rest-service", absolute = true)
+  public Response getIcebergRestServiceUri(@QueryParam("metalake") String metalake) {
+    return Utils.ok(new IcebergRESTServiceResponse(resolveUri(metalake)));
+  }
+
+  private String resolveUri(String metalake) {
+    if (!GravitinoEnv.getInstance().auxServiceManager().isAuxServiceRegistered(AUX_SERVICE_NAME)) {
+      return null;
+    }
+
+    Config config = GravitinoEnv.getInstance().config();
+    String servedMetalake = config.getRawString(SERVED_METALAKE_KEY, "");
+    if (StringUtils.isNotBlank(metalake)
+        && StringUtils.isNotBlank(servedMetalake)
+        && !servedMetalake.equals(metalake)) {
+      // The Iceberg REST server serves exactly one metalake. Routing a different metalake's
+      // catalogs at it would 404 on every request, so report it as unavailable instead.
+      return null;
+    }
+
+    JettyServerConfig icebergRestConfig = JettyServerConfig.fromConfig(config, CONFIG_PREFIX);
+    String host = icebergRestConfig.getHost();
+    if (isWildcardHost(host)) {
+      // The Iceberg REST server binds to all interfaces, so it has no single externally
+      // reachable address of its own. The caller already reached this Gravitino server at some
+      // resolvable host, so reuse it — this holds whenever both services share a host, which is
+      // the common case, and callers with a genuinely split topology can still set
+      // gravitino.iceberg.rest-uri manually.
+      host = httpRequest.getServerName();
+    }
+    String scheme = icebergRestConfig.isEnableHttps() ? "https" : "http";
+    return String.format("%s://%s:%d/iceberg", scheme, host, icebergRestConfig.getHttpPort());
+  }
+
+  private static boolean isWildcardHost(String host) {
+    return StringUtils.isBlank(host) || "0.0.0.0".equals(host) || "::".equals(host);
+  }
+}
diff --git a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java
index 1be5ef43bc..968e26fb30 100644
--- a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java
+++ b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java
@@ -131,7 +131,6 @@ public class TrinoConnectorIT extends BaseIT {
         trinoConfDir,
         System.getenv("GRAVITINO_ROOT_DIR") + "/trino-connector/build/libs",
         getGravitinoServerPort(),
-        getIcebergRestServicePort(),
         metalakeName);
     Assertions.assertTrue(
         containerSuite.getTrinoContainer().checkSyncCatalogFromGravitino(5, catalogName),
diff --git a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.java b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.java
index 24d33cbf2e..e5be0c11c4 100644
--- a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.java
+++ b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.java
@@ -120,7 +120,6 @@ public class TrinoQueryITBase {
 
       trinoITContainers.launch(
           baseIT.getGravitinoServerPort(),
-          baseIT.getIcebergRestServicePort(),
           hiveRuntimeVersion,
           isTrinoConnectorTest,
           trinoWorkerNum,
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
index 50af268066..2c1f795afb 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
@@ -31,18 +31,15 @@ import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 import java.util.Properties;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.regex.Pattern;
 import java.util.stream.Collectors;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.gravitino.trino.connector.security.GravitinoAuthProvider;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
 
 /** Gravitino config. */
 public class GravitinoConfig {
 
-  private static final Logger LOG = LoggerFactory.getLogger(GravitinoConfig.class);
-
   // Trino config keys
   /** The Trino discovery URI. */
   private static final String TRINO_DISCOVERY_URI = "discovery.uri";
@@ -86,6 +83,9 @@ public class GravitinoConfig {
   private static final Map<String, ConfigEntry> CONFIG_DEFINITIONS = new HashMap<>();
   private final Map<String, String> config;
   private final List<Pattern> skipCatalogPatternList;
+  // Iceberg REST server endpoints discovered from the Gravitino server, keyed by metalake. Written
+  // by the catalog connector manager's periodic poll and read on every Iceberg catalog load.
+  private final Map<String, String> discoveredIcebergRestUriByMetalake = new ConcurrentHashMap<>();
 
   // Gravitino config entity
   private static final ConfigEntry GRAVITINO_URI =
@@ -270,20 +270,13 @@ public class GravitinoConfig {
           "3600",
           false);
 
-  private static final ConfigEntry GRAVITINO_ICEBERG_REST_ENABLED =
-      new ConfigEntry(
-          "gravitino.iceberg.rest-enabled",
-          "When true, lakehouse-iceberg catalogs are loaded through the Gravitino Iceberg REST "
-              + "server instead of being translated into a Trino JDBC or Hive metastore Iceberg "
-              + "catalog. Requires gravitino.iceberg.rest-uri.",
-          "true",
-          false);
-
   private static final ConfigEntry GRAVITINO_ICEBERG_REST_URI =
       new ConfigEntry(
           "gravitino.iceberg.rest-uri",
-          "The endpoint of the Gravitino Iceberg REST server, for example "
-              + "http://localhost:9001/iceberg.",
+          "The endpoint of the Gravitino Iceberg REST server. Discovered automatically from the "
+              + "Gravitino server by default; set this only to override the discovered value, "
+              + "for example when the Iceberg REST server is not reachable at the address the "
+              + "Gravitino server itself reports.",
           "",
           false);
 
@@ -325,28 +318,6 @@ public class GravitinoConfig {
           "Config `gravitino.trino.skip-catalog-patterns` is invalid because it contains an illegal regular expression",
           e);
     }
-    warnOnMissingIcebergRestUri();
-  }
-
-  /**
-   * Warns at startup when the Iceberg REST routing is on but has no endpoint. Without this, the
-   * failure only surfaces once a lakehouse-iceberg catalog is loaded, and that error is swallowed
-   * by the catalog refresh loop, leaving the user with an unexplained missing catalog.
-   */
-  private void warnOnMissingIcebergRestUri() {
-    // Only the statically configured connector warns; the dynamic per-catalog ones would repeat it.
-    if (isDynamicConnector()
-        || !isIcebergRestEnabled()
-        || StringUtils.isNotBlank(getIcebergRestUri())) {
-      return;
-    }
-    LOG.warn(
-        "'{}' is enabled but '{}' is not set, so every lakehouse-iceberg catalog will fail to "
-            + "load. Set the Iceberg REST server endpoint, or set '{}=false' to load Iceberg "
-            + "catalogs through their catalog backend instead.",
-        GRAVITINO_ICEBERG_REST_ENABLED.key,
-        GRAVITINO_ICEBERG_REST_URI.key,
-        GRAVITINO_ICEBERG_REST_ENABLED.key);
   }
 
   /**
@@ -738,25 +709,40 @@ public class GravitinoConfig {
   }
 
   /**
-   * Returns whether lakehouse-iceberg catalogs are routed through the Gravitino Iceberg REST
-   * server.
+   * Sets the Iceberg REST server endpoint discovered from the Gravitino server for the given
+   * metalake. Called by the catalog connector manager's periodic metalake poll; ignored for a
+   * metalake where {@code gravitino.iceberg.rest-uri} is explicitly configured, which always takes
+   * precedence.
    *
-   * @return true if the Iceberg REST routing is enabled
+   * @param metalake the metalake the endpoint was discovered for
+   * @param uri the discovered endpoint, or {@code null} when the Iceberg REST server is not running
+   *     or does not serve this metalake
    */
-  public boolean isIcebergRestEnabled() {
-    return Boolean.parseBoolean(
-        config.getOrDefault(
-            GRAVITINO_ICEBERG_REST_ENABLED.key, GRAVITINO_ICEBERG_REST_ENABLED.defaultValue));
+  public void setDiscoveredIcebergRestUri(String metalake, String uri) {
+    if (StringUtils.isBlank(uri)) {
+      discoveredIcebergRestUriByMetalake.remove(metalake);
+    } else {
+      discoveredIcebergRestUriByMetalake.put(metalake, uri);
+    }
   }
 
   /**
-   * Retrieves the endpoint of the Gravitino Iceberg REST server.
+   * Retrieves the Iceberg REST server endpoint to route the given metalake's lakehouse-iceberg
+   * catalogs through. Prefers an explicitly configured {@code gravitino.iceberg.rest-uri};
+   * otherwise falls back to the endpoint discovered from the Gravitino server for this metalake, if
+   * any.
    *
-   * @return the Iceberg REST server endpoint, or an empty string if not configured
+   * @param metalake the metalake to resolve the endpoint for
+   * @return the Iceberg REST server endpoint, or an empty string when none is available
    */
-  public String getIcebergRestUri() {
-    return config.getOrDefault(
-        GRAVITINO_ICEBERG_REST_URI.key, GRAVITINO_ICEBERG_REST_URI.defaultValue);
+  public String getIcebergRestUri(String metalake) {
+    String configured =
+        config.getOrDefault(
+            GRAVITINO_ICEBERG_REST_URI.key, GRAVITINO_ICEBERG_REST_URI.defaultValue);
+    if (StringUtils.isNotBlank(configured)) {
+      return configured;
+    }
+    return discoveredIcebergRestUriByMetalake.getOrDefault(metalake, "");
   }
 
   /**
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java
index 34872d2e2f..e11c16b30b 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java
@@ -197,6 +197,7 @@ public class CatalogConnectorManager {
         try {
           GravitinoMetalake metalake = metalakes.get(usedMetalake);
           LOG.debug("Load metalake: {}", usedMetalake);
+          refreshIcebergRestUri(usedMetalake);
           loadCatalogs(metalake);
         } catch (Exception e) {
           LOG.error("Load Metalake {} failed.", usedMetalake, e);
@@ -207,6 +208,23 @@ public class CatalogConnectorManager {
     }
   }
 
+  /**
+   * Asks the Gravitino server whether it has an Iceberg REST server running for this metalake, and
+   * caches the answer on the shared {@link GravitinoConfig} for {@code IcebergConnectorAdapter} to
+   * read on the next catalog load. Failures — including talking to a Gravitino server older than
+   * this endpoint — must not interrupt catalog loading, so they are swallowed here; Iceberg
+   * catalogs simply keep their last known routing decision until the next successful poll.
+   */
+  private void refreshIcebergRestUri(String metalakeName) {
+    try {
+      config.setDiscoveredIcebergRestUri(
+          metalakeName, gravitinoClient.icebergRestServiceUri(metalakeName).orElse(null));
+    } catch (Exception e) {
+      LOG.debug(
+          "Failed to query the Iceberg REST service endpoint for metalake {}.", metalakeName, e);
+    }
+  }
+
   /**
    * Retrieves a metalake by its name.
    *
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
index dd8a492e1d..5d81fd02ab 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
@@ -151,18 +151,21 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
    * @param catalog the Gravitino catalog to load
    * @param gravitinoConfig the connector configuration holding the Iceberg REST server endpoint
    * @return the Trino Iceberg connector config
-   * @throws TrinoException if {@code gravitino.iceberg.rest-uri} is not configured
+   * @throws TrinoException if no Iceberg REST server endpoint is configured or discovered for this
+   *     catalog's metalake
    */
   public Map<String, String> buildIcebergRestProperties(
       GravitinoCatalog catalog, GravitinoConfig gravitinoConfig) {
-    String restUri = gravitinoConfig.getIcebergRestUri();
+    String restUri = gravitinoConfig.getIcebergRestUri(catalog.getMetalake());
     if (StringUtils.isBlank(restUri)) {
+      // The caller only reaches this method once it has already confirmed a non-blank URI, so
+      // this is defensive: it can only fire if that URI disappeared between the two calls.
       throw new TrinoException(
           GravitinoErrorCode.GRAVITINO_MISSING_CONFIG,
-          "Missing required config 'gravitino.iceberg.rest-uri'. Set it to the Gravitino Iceberg "
-              + "REST server endpoint, for example http://localhost:9001/iceberg, or set "
-              + "'gravitino.iceberg.rest-enabled=false' to load Iceberg catalogs through their "
-              + "catalog backend instead.");
+          "No Iceberg REST server endpoint is available for metalake '"
+              + catalog.getMetalake()
+              + "'. Set 'gravitino.iceberg.rest-uri' to override the address the Gravitino "
+              + "server reports.");
     }
 
     Map<String, String> config = new HashMap<>();
@@ -189,19 +192,6 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
     // The server echoes `prefix` back as a config default, so setting it here is belt-and-braces.
     config.put(TRINO_ICEBERG_REST_WAREHOUSE, catalog.getName());
     config.put(TRINO_ICEBERG_REST_PREFIX, catalog.getName());
-
-    if (!gravitinoConfig.singleMetalakeMode()) {
-      // The IRC serves exactly one metalake, and the prefix carries only the catalog name, so two
-      // metalakes holding a same-named catalog both resolve to whichever one the IRC was started
-      // with.
-      LOG.warn(
-          "Catalog '{}' in metalake '{}' is routed to the Iceberg REST server using the catalog "
-              + "name alone. In multi-metalake mode this is ambiguous: the Iceberg REST server "
-              + "serves a single metalake, so a same-named catalog in another metalake resolves to "
-              + "the same prefix.",
-          catalog.getName(),
-          catalog.getMetalake());
-    }
     return config;
   }
 
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java
index 1480dc13d4..4cdd9cd1c0 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java
@@ -24,6 +24,7 @@ import io.trino.spi.session.PropertyMetadata;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import org.apache.commons.lang3.StringUtils;
 import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
 import org.apache.gravitino.credential.Credential;
 import org.apache.gravitino.trino.connector.GravitinoConfig;
@@ -64,10 +65,12 @@ public class IcebergConnectorAdapter implements CatalogConnectorAdapter {
   public Map<String, String> buildInternalConnectorConfig(
       GravitinoCatalog catalog, Credential[] credentials) throws Exception {
     // The catalog backend describes how Gravitino stores the metadata; it does not decide how
-    // Trino reaches the data. Unless the routing is disabled, every catalog is loaded through the
-    // Gravitino Iceberg REST server, the only path that supports temporary credentials.
-    // A catalog that already has a REST backend keeps pointing at its own configured endpoint.
-    if (config.isIcebergRestEnabled()
+    // Trino reaches the data. Whenever the Gravitino server reports a running Iceberg REST
+    // server for this catalog's metalake, the catalog is loaded through it, the only path that
+    // supports temporary credentials. A catalog that already has a REST backend keeps pointing at
+    // its own configured endpoint. If the server reports nothing, this falls back to translating
+    // catalog-backend as before — nothing to configure either way.
+    if (StringUtils.isNotBlank(config.getIcebergRestUri(catalog.getMetalake()))
         && !REST_CATALOG_BACKEND.equalsIgnoreCase(
             catalog.getProperty(IcebergConstants.CATALOG_BACKEND, null))) {
       // `credentials` is intentionally unused here: with vended credentials enabled, Trino obtains
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
index 357280cf90..0528006823 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
@@ -304,8 +304,8 @@ public class TestGravitinoConfig {
   public void testIcebergRestConfigDefaults() {
     GravitinoConfig config = new GravitinoConfig(ImmutableMap.of("gravitino.metalake", "user_001"));
 
-    assertTrue(config.isIcebergRestEnabled());
-    assertEquals("", config.getIcebergRestUri());
+    // Nothing configured, and nothing discovered yet.
+    assertEquals("", config.getIcebergRestUri("user_001"));
     assertTrue(config.getIcebergRestCatalogConfig().isEmpty());
   }
 
@@ -315,8 +315,6 @@ public class TestGravitinoConfig {
         ImmutableMap.of(
             "gravitino.metalake",
             "user_001",
-            "gravitino.iceberg.rest-enabled",
-            "false",
             "gravitino.iceberg.rest-uri",
             "http://127.0.0.1:9001/iceberg",
             "gravitino.iceberg.rest-catalog.security",
@@ -325,8 +323,9 @@ public class TestGravitinoConfig {
             "client_id:client_secret");
     GravitinoConfig config = new GravitinoConfig(configMap);
 
-    assertFalse(config.isIcebergRestEnabled());
-    assertEquals("http://127.0.0.1:9001/iceberg", config.getIcebergRestUri());
+    // A manually configured URI applies regardless of metalake.
+    assertEquals("http://127.0.0.1:9001/iceberg", config.getIcebergRestUri("user_001"));
+    assertEquals("http://127.0.0.1:9001/iceberg", config.getIcebergRestUri("other_metalake"));
 
     Map<String, String> restCatalogConfig = config.getIcebergRestCatalogConfig();
     assertEquals(2, restCatalogConfig.size());
@@ -335,6 +334,38 @@ public class TestGravitinoConfig {
         "client_id:client_secret", restCatalogConfig.get("iceberg.rest-catalog.oauth2.credential"));
   }
 
+  @Test
+  public void testDiscoveredIcebergRestUriIsPerMetalake() {
+    GravitinoConfig config = new GravitinoConfig(ImmutableMap.of("gravitino.metalake", "user_001"));
+
+    config.setDiscoveredIcebergRestUri("metalake_a", "http://irc-a:9001/iceberg");
+    config.setDiscoveredIcebergRestUri("metalake_b", "http://irc-b:9001/iceberg");
+
+    assertEquals("http://irc-a:9001/iceberg", config.getIcebergRestUri("metalake_a"));
+    assertEquals("http://irc-b:9001/iceberg", config.getIcebergRestUri("metalake_b"));
+    // Unknown/unmatched metalakes fall back to nothing.
+    assertEquals("", config.getIcebergRestUri("metalake_c"));
+
+    // Clearing (e.g. the server stopped reporting an endpoint) removes it again.
+    config.setDiscoveredIcebergRestUri("metalake_a", null);
+    assertEquals("", config.getIcebergRestUri("metalake_a"));
+  }
+
+  @Test
+  public void testManualIcebergRestUriOverridesDiscovery() {
+    GravitinoConfig config =
+        new GravitinoConfig(
+            ImmutableMap.of(
+                "gravitino.metalake",
+                "user_001",
+                "gravitino.iceberg.rest-uri",
+                "http://manual:9001/iceberg"));
+
+    config.setDiscoveredIcebergRestUri("user_001", "http://discovered:9001/iceberg");
+
+    assertEquals("http://manual:9001/iceberg", config.getIcebergRestUri("user_001"));
+  }
+
   @Test
   public void testToCatalogConfigWithIcebergRestProperties() {
     ImmutableMap<String, String> configMap =
@@ -353,18 +384,6 @@ public class TestGravitinoConfig {
     assertTrue(catalogConfig.contains("\"gravitino.iceberg.rest-catalog.security\"='OAUTH2'"));
   }
 
-  @Test
-  public void testToCatalogConfigPropagatesIcebergRestEnabled() {
-    // The switch rides the exact-key loop rather than the prefix filter; if it fails to propagate,
-    // the coordinator and the workers build different configs for the same catalog.
-    GravitinoConfig config =
-        new GravitinoConfig(
-            ImmutableMap.of(
-                "gravitino.metalake", "user_001", "gravitino.iceberg.rest-enabled", "false"));
-
-    assertTrue(config.toCatalogConfig().contains("\"gravitino.iceberg.rest-enabled\"='false'"));
-  }
-
   private static boolean skipCatalog(String catalogName, GravitinoConfig config) {
     for (Pattern pattern : config.getSkipCatalogPatterns()) {
       if (pattern.matcher(catalogName).matches()) {
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
index f09e4d7469..8ad738188f 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
@@ -138,7 +138,7 @@ public class TestIcebergCatalogPropertyConverter {
     Catalog mockCatalog =
         TestGravitinoCatalog.mockCatalog(
             name, "lakehouse-iceberg", "test catalog", Catalog.Type.RELATIONAL, properties);
-    IcebergConnectorAdapter adapter = new IcebergConnectorAdapter(icebergRestDisabledConfig());
+    IcebergConnectorAdapter adapter = new IcebergConnectorAdapter(icebergRestUnavailableConfig());
 
     Map<String, String> config =
         adapter.buildInternalConnectorConfig(
@@ -178,7 +178,7 @@ public class TestIcebergCatalogPropertyConverter {
     Catalog mockCatalog =
         TestGravitinoCatalog.mockCatalog(
             name, "lakehouse-iceberg", "test catalog", Catalog.Type.RELATIONAL, properties);
-    IcebergConnectorAdapter adapter = new IcebergConnectorAdapter(icebergRestDisabledConfig());
+    IcebergConnectorAdapter adapter = new IcebergConnectorAdapter(icebergRestUnavailableConfig());
 
     Map<String, String> config =
         adapter.buildInternalConnectorConfig(
@@ -215,7 +215,7 @@ public class TestIcebergCatalogPropertyConverter {
     Catalog mockCatalog =
         TestGravitinoCatalog.mockCatalog(
             name, "lakehouse-iceberg", "test catalog", Catalog.Type.RELATIONAL, properties);
-    IcebergConnectorAdapter adapter = new IcebergConnectorAdapter(icebergRestDisabledConfig());
+    IcebergConnectorAdapter adapter = new IcebergConnectorAdapter(icebergRestUnavailableConfig());
 
     Map<String, String> config =
         adapter.buildInternalConnectorConfig(
@@ -242,7 +242,8 @@ public class TestIcebergCatalogPropertyConverter {
             .build();
 
     Map<String, String> config =
-        buildConnectorConfig("catalog1", properties, icebergRestEnabledConfig(ImmutableMap.of()));
+        buildConnectorConfig(
+            "catalog1", properties, icebergRestConfiguredConfig(ImmutableMap.of()));
 
     Assertions.assertEquals("rest", config.get("iceberg.catalog.type"));
     Assertions.assertEquals(
@@ -268,7 +269,8 @@ public class TestIcebergCatalogPropertyConverter {
             .build();
 
     Map<String, String> config =
-        buildConnectorConfig("catalog1", properties, icebergRestEnabledConfig(ImmutableMap.of()));
+        buildConnectorConfig(
+            "catalog1", properties, icebergRestConfiguredConfig(ImmutableMap.of()));
 
     Assertions.assertEquals("rest", config.get("iceberg.catalog.type"));
     Assertions.assertEquals("catalog1", config.get("iceberg.rest-catalog.prefix"));
@@ -285,7 +287,8 @@ public class TestIcebergCatalogPropertyConverter {
             .build();
 
     Map<String, String> config =
-        buildConnectorConfig("catalog1", properties, icebergRestEnabledConfig(ImmutableMap.of()));
+        buildConnectorConfig(
+            "catalog1", properties, icebergRestConfiguredConfig(ImmutableMap.of()));
 
     Assertions.assertEquals("rest", config.get("iceberg.catalog.type"));
     Assertions.assertEquals(
@@ -305,7 +308,7 @@ public class TestIcebergCatalogPropertyConverter {
             .build();
 
     Map<String, String> config =
-        buildConnectorConfig("catalog1", properties, icebergRestDisabledConfig());
+        buildConnectorConfig("catalog1", properties, icebergRestUnavailableConfig());
 
     Assertions.assertEquals("jdbc", config.get("iceberg.catalog.type"));
     Assertions.assertEquals(
@@ -315,18 +318,85 @@ public class TestIcebergCatalogPropertyConverter {
   }
 
   @Test
-  public void testBuildConnectorPropertiesMissingIcebergRestUri() {
+  public void testBuildConnectorPropertiesFallsBackWhenNoIcebergRestUriIsAvailable()
+      throws Exception {
     Map<String, String> properties =
         ImmutableMap.<String, String>builder()
             .put("uri", "jdbc:postgresql://localhost:5432/iceberg")
             .put("catalog-backend", "jdbc")
             .put("jdbc-driver", "org.postgresql.Driver")
             .build();
-    GravitinoConfig gravitinoConfig =
-        new GravitinoConfig(ImmutableMap.of("gravitino.metalake", "test"));
+
+    // Neither a manual gravitino.iceberg.rest-uri nor a discovered one for this metalake: the
+    // routing gate never fires, so this is the ordinary backend-translation path, not an error.
+    Map<String, String> config =
+        buildConnectorConfig("catalog1", properties, icebergRestUnavailableConfig());
+
+    Assertions.assertEquals("jdbc", config.get("iceberg.catalog.type"));
+    Assertions.assertNull(config.get("iceberg.rest-catalog.uri"));
+  }
+
+  @Test
+  public void testBuildIcebergRestPropertiesThrowsOnBlankUri() {
+    // buildIcebergRestProperties keeps its own defensive check even though
+    // IcebergConnectorAdapter's routing gate means callers can no longer reach it with a blank
+    // URI under normal operation.
+    Catalog mockCatalog =
+        TestGravitinoCatalog.mockCatalog(
+            "catalog1",
+            "lakehouse-iceberg",
+            "test catalog",
+            Catalog.Type.RELATIONAL,
+            ImmutableMap.of("catalog-backend", "jdbc"));
+    GravitinoCatalog catalog = new GravitinoCatalog("test", mockCatalog);
+    IcebergCatalogPropertyConverter converter = new IcebergCatalogPropertyConverter();
 
     Assertions.assertThrows(
-        TrinoException.class, () -> buildConnectorConfig("catalog1", properties, gravitinoConfig));
+        TrinoException.class,
+        () -> converter.buildIcebergRestProperties(catalog, icebergRestUnavailableConfig()));
+  }
+
+  @Test
+  public void testBuildConnectorPropertiesRoutesThroughDiscoveredIcebergRestUri() throws Exception {
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .put("catalog-backend", "jdbc")
+            .put("uri", "jdbc:postgresql://localhost:5432/iceberg")
+            .put("jdbc-driver", "org.postgresql.Driver")
+            .build();
+
+    // No manual gravitino.iceberg.rest-uri: only a per-metalake value discovered from the
+    // Gravitino server, exactly as CatalogConnectorManager's periodic poll would set it.
+    Map<String, String> config =
+        buildConnectorConfig(
+            "catalog1",
+            properties,
+            icebergRestDiscoveredConfig("test", "http://discovered:9001/iceberg"));
+
+    Assertions.assertEquals("rest", config.get("iceberg.catalog.type"));
+    Assertions.assertEquals(
+        "http://discovered:9001/iceberg", config.get("iceberg.rest-catalog.uri"));
+  }
+
+  @Test
+  public void testBuildConnectorPropertiesIgnoresDiscoveryForOtherMetalakes() throws Exception {
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .put("catalog-backend", "jdbc")
+            .put("uri", "jdbc:postgresql://localhost:5432/iceberg")
+            .put("jdbc-driver", "org.postgresql.Driver")
+            .build();
+
+    // Discovery reported an endpoint for a different metalake than the one this catalog belongs
+    // to (the mock catalog's metalake is "test"); it must not leak across metalakes.
+    Map<String, String> config =
+        buildConnectorConfig(
+            "catalog1",
+            properties,
+            icebergRestDiscoveredConfig("other_metalake", "http://other:9001/iceberg"));
+
+    Assertions.assertEquals("jdbc", config.get("iceberg.catalog.type"));
+    Assertions.assertNull(config.get("iceberg.rest-catalog.uri"));
   }
 
   @Test
@@ -339,7 +409,7 @@ public class TestIcebergCatalogPropertyConverter {
             .put("warehouse", "s3://bucket/warehouse/")
             .build();
     GravitinoConfig gravitinoConfig =
-        icebergRestEnabledConfig(
+        icebergRestConfiguredConfig(
             ImmutableMap.of(
                 "gravitino.iceberg.rest-catalog.security", "OAUTH2",
                 "gravitino.iceberg.rest-catalog.oauth2.credential", "client_id:client_secret",
@@ -368,7 +438,7 @@ public class TestIcebergCatalogPropertyConverter {
         buildConnectorConfig(
             "catalog1",
             properties,
-            icebergRestEnabledConfig(
+            icebergRestConfiguredConfig(
                 ImmutableMap.of("gravitino.client.session.forwardUser", "true")));
     Assertions.assertEquals("USER", config.get("iceberg.rest-catalog.session"));
 
@@ -376,14 +446,15 @@ public class TestIcebergCatalogPropertyConverter {
         buildConnectorConfig(
             "catalog1",
             properties,
-            icebergRestEnabledConfig(
+            icebergRestConfiguredConfig(
                 ImmutableMap.of(
                     "gravitino.client.session.forwardUser", "true",
                     "gravitino.iceberg.rest-catalog.session", "NONE")));
     Assertions.assertEquals("NONE", explicitConfig.get("iceberg.rest-catalog.session"));
 
     Map<String, String> defaultConfig =
-        buildConnectorConfig("catalog1", properties, icebergRestEnabledConfig(ImmutableMap.of()));
+        buildConnectorConfig(
+            "catalog1", properties, icebergRestConfiguredConfig(ImmutableMap.of()));
     Assertions.assertNull(defaultConfig.get("iceberg.rest-catalog.session"));
   }
 
@@ -397,7 +468,7 @@ public class TestIcebergCatalogPropertyConverter {
                 "warehouse", "s3://bucket/warehouse/",
                 "s3-region", "us-east-1",
                 "s3-endpoint", "http://minio:9000"),
-            icebergRestEnabledConfig(ImmutableMap.of()));
+            icebergRestConfiguredConfig(ImmutableMap.of()));
     Assertions.assertEquals("true", s3Config.get("fs.native-s3.enabled"));
     Assertions.assertEquals("us-east-1", s3Config.get("s3.region"));
     Assertions.assertEquals("http://minio:9000", s3Config.get("s3.endpoint"));
@@ -407,7 +478,7 @@ public class TestIcebergCatalogPropertyConverter {
         buildConnectorConfig(
             "catalog1",
             ImmutableMap.of("catalog-backend", "jdbc", "warehouse", "gs://bucket/warehouse/"),
-            icebergRestEnabledConfig(ImmutableMap.of()));
+            icebergRestConfiguredConfig(ImmutableMap.of()));
     Assertions.assertEquals("true", gcsConfig.get("fs.native-gcs.enabled"));
     Assertions.assertNull(gcsConfig.get("fs.native-s3.enabled"));
 
@@ -416,14 +487,14 @@ public class TestIcebergCatalogPropertyConverter {
             "catalog1",
             ImmutableMap.of(
                 "catalog-backend", "jdbc", "warehouse", "abfss://container@account/warehouse/"),
-            icebergRestEnabledConfig(ImmutableMap.of()));
+            icebergRestConfiguredConfig(ImmutableMap.of()));
     Assertions.assertEquals("true", azureConfig.get("fs.native-azure.enabled"));
 
     Map<String, String> hdfsConfig =
         buildConnectorConfig(
             "catalog1",
             ImmutableMap.of("catalog-backend", "jdbc", "warehouse", "hdfs://namenode:9000/wh"),
-            icebergRestEnabledConfig(ImmutableMap.of()));
+            icebergRestConfiguredConfig(ImmutableMap.of()));
     Assertions.assertEquals("true", hdfsConfig.get("fs.hadoop.enabled"));
     Assertions.assertNull(hdfsConfig.get("fs.native-s3.enabled"));
     Assertions.assertNull(hdfsConfig.get("fs.native-gcs.enabled"));
@@ -441,7 +512,8 @@ public class TestIcebergCatalogPropertyConverter {
             .build();
 
     Map<String, String> config =
-        buildConnectorConfig("catalog1", properties, icebergRestEnabledConfig(ImmutableMap.of()));
+        buildConnectorConfig(
+            "catalog1", properties, icebergRestConfiguredConfig(ImmutableMap.of()));
 
     Assertions.assertEquals("true", config.get("iceberg.table-statistics-enabled"));
     // A catalog can override a derived default, so a Trino release renaming it is not a blocker.
@@ -470,7 +542,7 @@ public class TestIcebergCatalogPropertyConverter {
 
     Map<String, String> config =
         buildConnectorConfig(
-            "catalog1", properties, icebergRestEnabledConfig(ImmutableMap.of()), credentials);
+            "catalog1", properties, icebergRestConfiguredConfig(ImmutableMap.of()), credentials);
 
     // The REST protocol vends a fresh credential per table access, so the catalog-level snapshot
     // must not be pinned into the connector config.
@@ -482,7 +554,7 @@ public class TestIcebergCatalogPropertyConverter {
 
     // The backend path still applies them.
     Map<String, String> legacyConfig =
-        buildConnectorConfig("catalog1", properties, icebergRestDisabledConfig(), credentials);
+        buildConnectorConfig("catalog1", properties, icebergRestUnavailableConfig(), credentials);
     Assertions.assertEquals("root", legacyConfig.get("iceberg.jdbc-catalog.connection-user"));
     Assertions.assertEquals("AKIAEXAMPLE", legacyConfig.get("hive.s3.aws-access-key"));
   }
@@ -500,7 +572,8 @@ public class TestIcebergCatalogPropertyConverter {
             .build();
 
     Map<String, String> config =
-        buildConnectorConfig("catalog1", properties, icebergRestEnabledConfig(ImmutableMap.of()));
+        buildConnectorConfig(
+            "catalog1", properties, icebergRestConfiguredConfig(ImmutableMap.of()));
 
     // A catalog property must never redirect the connector at another endpoint or catalog.
     Assertions.assertEquals("rest", config.get("iceberg.catalog.type"));
@@ -523,7 +596,7 @@ public class TestIcebergCatalogPropertyConverter {
         buildConnectorConfig(
             "catalog1",
             properties,
-            icebergRestEnabledConfig(
+            icebergRestConfiguredConfig(
                 ImmutableMap.of("gravitino.iceberg.rest-catalog.security", "OAUTH2")));
 
     // Cluster-level operational settings outrank per-catalog properties.
@@ -538,7 +611,7 @@ public class TestIcebergCatalogPropertyConverter {
           buildConnectorConfig(
               "catalog1",
               ImmutableMap.of("catalog-backend", "jdbc", "warehouse", warehouse),
-              icebergRestEnabledConfig(ImmutableMap.of()));
+              icebergRestConfiguredConfig(ImmutableMap.of()));
       Assertions.assertEquals(
           "true", config.get("fs.native-s3.enabled"), "warehouse: " + warehouse);
     }
@@ -548,7 +621,7 @@ public class TestIcebergCatalogPropertyConverter {
         buildConnectorConfig(
             "catalog1",
             ImmutableMap.of("catalog-backend", "jdbc", "warehouse", "gt_iceberg_rest"),
-            icebergRestEnabledConfig(ImmutableMap.of()));
+            icebergRestConfiguredConfig(ImmutableMap.of()));
     Assertions.assertEquals("true", schemeless.get("fs.hadoop.enabled"));
     Assertions.assertNull(schemeless.get("fs.native-s3.enabled"));
 
@@ -557,7 +630,7 @@ public class TestIcebergCatalogPropertyConverter {
         buildConnectorConfig(
             "catalog1",
             ImmutableMap.of("catalog-backend", "jdbc"),
-            icebergRestEnabledConfig(ImmutableMap.of()));
+            icebergRestConfiguredConfig(ImmutableMap.of()));
     Assertions.assertEquals("true", noWarehouse.get("fs.hadoop.enabled"));
     Assertions.assertNull(noWarehouse.get("fs.native-s3.enabled"));
     Assertions.assertNull(noWarehouse.get("fs.native-gcs.enabled"));
@@ -571,7 +644,7 @@ public class TestIcebergCatalogPropertyConverter {
                 "catalog-backend", "jdbc",
                 "warehouse", "oss://bucket/wh",
                 "credential-providers", "oss-token"),
-            icebergRestEnabledConfig(ImmutableMap.of()));
+            icebergRestConfiguredConfig(ImmutableMap.of()));
     Assertions.assertEquals("true", oss.get("fs.hadoop.enabled"));
     Assertions.assertNull(oss.get("fs.native-s3.enabled"));
   }
@@ -586,7 +659,7 @@ public class TestIcebergCatalogPropertyConverter {
                 "warehouse", "s3://bucket/wh",
                 "s3-endpoint", "http://minio:9000",
                 "s3-path-style-access", "true"),
-            icebergRestEnabledConfig(ImmutableMap.of()));
+            icebergRestConfiguredConfig(ImmutableMap.of()));
 
     // S3-compatible stores such as MinIO need path-style addressing to resolve the bucket.
     Assertions.assertEquals("true", config.get("s3.path-style-access"));
@@ -599,7 +672,7 @@ public class TestIcebergCatalogPropertyConverter {
         buildConnectorConfig(
             "catalog1",
             ImmutableMap.of("catalog-backend", "REST", "uri", "http://other-irc:9001/iceberg"),
-            icebergRestEnabledConfig(ImmutableMap.of()));
+            icebergRestConfiguredConfig(ImmutableMap.of()));
 
     Assertions.assertEquals(
         "http://other-irc:9001/iceberg", config.get("iceberg.rest-catalog.uri"));
@@ -619,12 +692,13 @@ public class TestIcebergCatalogPropertyConverter {
         .buildInternalConnectorConfig(new GravitinoCatalog("test", mockCatalog), credentials);
   }
 
-  private static GravitinoConfig icebergRestDisabledConfig() {
-    return new GravitinoConfig(
-        ImmutableMap.of("gravitino.metalake", "test", "gravitino.iceberg.rest-enabled", "false"));
+  private static GravitinoConfig icebergRestUnavailableConfig() {
+    // No manual gravitino.iceberg.rest-uri, and nothing discovered for this metalake: the
+    // connector has no endpoint to route through, so catalogs fall back to their own backend.
+    return new GravitinoConfig(ImmutableMap.of("gravitino.metalake", "test"));
   }
 
-  private static GravitinoConfig icebergRestEnabledConfig(Map<String, String> extraConfig) {
+  private static GravitinoConfig icebergRestConfiguredConfig(Map<String, String> extraConfig) {
     return new GravitinoConfig(
         ImmutableMap.<String, String>builder()
             .put("gravitino.metalake", "test")
@@ -632,4 +706,10 @@ public class TestIcebergCatalogPropertyConverter {
             .putAll(extraConfig)
             .build());
   }
+
+  private static GravitinoConfig icebergRestDiscoveredConfig(String metalake, String uri) {
+    GravitinoConfig config = new GravitinoConfig(ImmutableMap.of("gravitino.metalake", metalake));
+    config.setDiscoveredIcebergRestUri(metalake, uri);
+    return config;
+  }
 }


(gravitino) 12/13: [Cherry-pick to branch-1.3] fix(trino): secure dynamic catalog credentials

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diqiu50 pushed a commit to branch trino-irc-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit aeec51586d0ae211cd9c8c6ddd1b5772d87ab35a
Author: yuhui <hu...@datastrato.com>
AuthorDate: Mon Aug 24 15:29:27 2026 +0000

    [Cherry-pick to branch-1.3] fix(trino): secure dynamic catalog credentials
    
    (cherry picked from commit 6032d8d368901e9ca3d02cf741e9fee535f59a9b)
---
 .../web/rest/IcebergRESTServiceOperations.java     |  1 +
 .../web/rest/TestIcebergRESTServiceOperations.java | 11 +++++++
 .../gravitino/trino/connector/GravitinoConfig.java | 35 ++++++++++++++++++++--
 .../trino/connector/GravitinoConnectorFactory.java |  3 ++
 .../trino/connector/catalog/CatalogRegister.java   |  4 +--
 .../trino/connector/TestGravitinoConfig.java       | 25 ++++++++++++++++
 .../connector/TestGravitinoConnectorFactory.java   |  3 ++
 7 files changed, 77 insertions(+), 5 deletions(-)

diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java
index ce672875e8..fb58da651d 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java
@@ -86,6 +86,7 @@ public class IcebergRESTServiceOperations {
    *     running, or does not serve the requested metalake
    */
   @GET
+  @Produces("application/vnd.gravitino.v1+json")
   @Timed(name = "iceberg-rest-service." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
   @ResponseMetered(name = "iceberg-rest-service", absolute = true)
   public Response getIcebergRestServiceUri(@QueryParam("metalake") String metalake) {
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java
index 5a559bf059..71b895f08b 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java
@@ -26,6 +26,7 @@ import static org.mockito.Mockito.when;
 import com.google.common.collect.ImmutableMap;
 import java.util.Map;
 import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Produces;
 import javax.ws.rs.core.Response;
 import org.apache.gravitino.auxiliary.AuxiliaryServiceManager;
 import org.apache.gravitino.dto.responses.IcebergRESTServiceResponse;
@@ -35,6 +36,16 @@ public class TestIcebergRESTServiceOperations {
 
   private static final String DYNAMIC_PROVIDER = "dynamic-config-provider";
 
+  @Test
+  public void testDiscoveryEndpointProducesVersionedJson() throws Exception {
+    Produces produces =
+        IcebergRESTServiceOperations.class
+            .getMethod("getIcebergRestServiceUri", String.class)
+            .getAnnotation(Produces.class);
+
+    assertEquals("application/vnd.gravitino.v1+json", produces.value()[0]);
+  }
+
   private static Map<String, String> withDynamicProvider(Map<String, String> extra) {
     return ImmutableMap.<String, String>builder()
         .put("catalog-config-provider", DYNAMIC_PROVIDER)
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
index 5cdeba701e..cb9d71a3ff 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
@@ -80,6 +80,13 @@ public class GravitinoConfig {
   /** The Trino Iceberg REST catalog property prefix. */
   private static final String TRINO_ICEBERG_REST_CATALOG_PREFIX = "iceberg.rest-catalog.";
 
+  /** Prefix for environment-variable references propagated to dynamic catalogs. */
+  static final String GRAVITINO_DYNAMIC_CATALOG_ENV_PREFIX =
+      "gravitino.dynamic-catalog.environment-variable.";
+
+  private static final Pattern ENVIRONMENT_VARIABLE_NAME =
+      Pattern.compile("[A-Za-z_][A-Za-z0-9_]*");
+
   private static final Map<String, ConfigEntry> CONFIG_DEFINITIONS = new HashMap<>();
   private final Map<String, String> config;
   private final List<Pattern> skipCatalogPatternList;
@@ -622,7 +629,8 @@ public class GravitinoConfig {
         continue;
       }
       String value = config.get(entry.getKey());
-      if (value != null) {
+      if (value != null
+          && !GravitinoConnectorFactory.isSecuritySensitivePropertyName(entry.getKey())) {
         stringList.add(String.format("\"%s\"='%s'", entry.getKey(), value));
       }
     }
@@ -631,11 +639,32 @@ public class GravitinoConfig {
     config.entrySet().stream()
         .filter(
             entry ->
-                entry.getKey().startsWith(GRAVITINO_CLIENT_CONFIG_PREFIX.key)
-                    || entry.getKey().startsWith(GRAVITINO_ICEBERG_REST_CATALOG_CONFIG_PREFIX.key))
+                (entry.getKey().startsWith(GRAVITINO_CLIENT_CONFIG_PREFIX.key)
+                        || entry
+                            .getKey()
+                            .startsWith(GRAVITINO_ICEBERG_REST_CATALOG_CONFIG_PREFIX.key))
+                    && !GravitinoConnectorFactory.isSecuritySensitivePropertyName(entry.getKey()))
         .forEach(
             entry ->
                 stringList.add(String.format("\"%s\"='%s'", entry.getKey(), entry.getValue())));
+    config.entrySet().stream()
+        .filter(entry -> entry.getKey().startsWith(GRAVITINO_DYNAMIC_CATALOG_ENV_PREFIX))
+        .forEach(
+            entry -> {
+              String propertyName =
+                  entry.getKey().substring(GRAVITINO_DYNAMIC_CATALOG_ENV_PREFIX.length());
+              String environmentVariable = entry.getValue();
+              if (propertyName.isEmpty()
+                  || !ENVIRONMENT_VARIABLE_NAME.matcher(environmentVariable).matches()) {
+                throw new TrinoException(
+                    GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT,
+                    String.format(
+                        "Invalid dynamic catalog environment-variable mapping '%s'='%s'",
+                        entry.getKey(), environmentVariable));
+              }
+              stringList.add(
+                  String.format("\"%s\"='${ENV:%s}'", propertyName, environmentVariable));
+            });
     return StringUtils.join(stringList, ',');
   }
 
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java
index b248ed7f82..a748c0ab58 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java
@@ -245,6 +245,9 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
 
   @VisibleForTesting
   static boolean isSecuritySensitivePropertyName(String propertyName) {
+    if (propertyName.startsWith(GravitinoConfig.GRAVITINO_DYNAMIC_CATALOG_ENV_PREFIX)) {
+      return false;
+    }
     String normalizedPropertyName = propertyName.toLowerCase(Locale.ROOT).replaceAll("[._-]", "");
     return SECURITY_SENSITIVE_PROPERTY_SUFFIXES.stream().anyMatch(normalizedPropertyName::endsWith);
   }
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
index fd971c3bce..11b183fd5d 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
@@ -472,14 +472,14 @@ public class CatalogRegister {
           throw e;
         } catch (Exception e) {
           failedException = e;
-          LOG.warn("Failed to execute command: {}", sql, e);
+          LOG.warn("Failed to execute command: {}", redactSecrets(sql), e);
           Thread.sleep(EXECUTE_QUERY_BACKOFF_TIME_SECOND * 1000);
         }
       }
       throw failedException;
     } catch (Exception e) {
       throw new TrinoException(
-          GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, "Failed to execute query: " + sql, e);
+          GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR, "Failed to execute query", e);
     }
   }
 
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
index d2792d75df..1f67109deb 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
@@ -390,6 +390,31 @@ public class TestGravitinoConfig {
     assertTrue(catalogConfig.contains("\"gravitino.iceberg.rest-catalog.security\"='OAUTH2'"));
   }
 
+  @Test
+  public void testToCatalogConfigPropagatesSecretReferencesInsteadOfSecretValues() {
+    GravitinoConfig config =
+        new GravitinoConfig(
+            ImmutableMap.of(
+                "gravitino.metalake", "user_001",
+                "gravitino.client.oauth2.credential", "client:management-secret",
+                "gravitino.iceberg.rest-catalog.oauth2.credential", "client:irc-secret",
+                "gravitino.dynamic-catalog.environment-variable.gravitino.client.oauth2.credential",
+                    "GRAVITINO_CLIENT_CREDENTIAL",
+                "gravitino.dynamic-catalog.environment-variable.gravitino.iceberg.rest-catalog.oauth2.credential",
+                    "IRC_CLIENT_CREDENTIAL"));
+
+    String catalogConfig = config.toCatalogConfig();
+
+    assertFalse(catalogConfig.contains("management-secret"));
+    assertFalse(catalogConfig.contains("irc-secret"));
+    assertTrue(
+        catalogConfig.contains(
+            "\"gravitino.client.oauth2.credential\"='${ENV:GRAVITINO_CLIENT_CREDENTIAL}'"));
+    assertTrue(
+        catalogConfig.contains(
+            "\"gravitino.iceberg.rest-catalog.oauth2.credential\"='${ENV:IRC_CLIENT_CREDENTIAL}'"));
+  }
+
   private static boolean skipCatalog(String catalogName, GravitinoConfig config) {
     for (Pattern pattern : config.getSkipCatalogPatterns()) {
       if (pattern.matcher(catalogName).matches()) {
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactory.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactory.java
index 0b0c71c6b6..7c30ced137 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactory.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactory.java
@@ -39,6 +39,9 @@ class TestGravitinoConnectorFactory {
             Map.entry("hive.s3.aws-secret-key", "secret-key"),
             Map.entry("authentication.token", "token"),
             Map.entry("oauth2.credential", "credential"),
+            Map.entry(
+                "gravitino.dynamic-catalog.environment-variable.oauth2.credential",
+                "OAUTH_CREDENTIAL"),
             Map.entry("tls.private_key", "private-key"),
             Map.entry("gravitino.uri", "uri"));
 


(gravitino) 09/13: [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Fix IRC discovery port default, worker propagation, and other review findings

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diqiu50 pushed a commit to branch trino-irc-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit 8e0ac683103b4b7cf25864b87acccd4322810f17
Author: diqiu50 <di...@apache.org>
AuthorDate: Mon Aug 24 15:57:54 2026 +0800

    [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Fix IRC discovery port default, worker propagation, and other review findings
    
    - Reported endpoint defaulted to the Gravitino server's own port (8090)
      whenever gravitino.iceberg-rest.httpPort was not set explicitly,
      because ServerConfig does not implement OverwriteDefaultConfig the
      way IcebergConfig does, so JettyServerConfig fell back to the
      Gravitino webserver's default instead of the Iceberg REST server's
      documented default (9001). Read the raw config with the correct
      defaults instead of going through JettyServerConfig.
    - The HTTPS branch used the HTTP port. Use the HTTPS port.
    - The discovered endpoint never reached Trino workers: only the
      coordinator runs the periodic discovery poll, and the discovered map
      lived only in that node's own GravitinoConfig. The coordinator now
      embeds the resolved endpoint into the catalog's own properties
      before registering it, so it travels to every node through the
      CREATE CATALOG statement Trino already replicates cluster-wide, the
      same way GravitinoCatalog.toJson already carries every other catalog
      property. IcebergConnectorAdapter reads it from the catalog instead
      of GravitinoConfig's discovered map, which only the manual override
      (plain local config, identical everywhere already) still uses.
    - Fixed an AuxiliaryServiceManager edit that had left @VisibleForTesting
      attached to the wrong method and a Javadoc block orphaned after an
      annotation instead of before the declaration it was meant to document.
    - Added Cache-Control: no-store to the discovery response, since the
      reported host can depend on the caller's own Host header, and
      broadened the wildcard-host match to cover [::] and the expanded
      IPv6 form.
    - Documented that discovery only affects a catalog at its next
      registration or reload, not retroactively, and that it applies to
      auxiliary-service IRC only, not standalone IRC.
    - Added unit tests: AuxiliaryServiceManager.isAuxServiceRegistered, and
      a full suite for IcebergRESTServiceOperations covering the port
      regression, https, explicit ports, wildcard/blank host fallback,
      metalake matching, and cache headers.
    
    (cherry picked from commit 26520805dd9c89ca9d76a5b5202b381f48744ff8)
---
 .../auxiliary/AuxiliaryServiceManager.java         |   2 +-
 .../auxiliary/TestAuxiliaryServiceManager.java     |  27 ++++
 docs/trino-connector/catalog-iceberg.md            |  35 +++--
 .../web/rest/IcebergRESTServiceOperations.java     |  70 +++++++--
 .../web/rest/TestIcebergRESTServiceOperations.java | 174 +++++++++++++++++++++
 .../gravitino/trino/connector/GravitinoConfig.java |  38 +++--
 .../trino/connector/catalog/CatalogRegister.java   |   9 +-
 .../iceberg/IcebergCatalogPropertyConverter.java   |  10 +-
 .../catalog/iceberg/IcebergConnectorAdapter.java   |  71 ++++++++-
 .../trino/connector/TestGravitinoConfig.java       |  31 +---
 .../TestIcebergCatalogPropertyConverter.java       |  61 +++++++-
 11 files changed, 451 insertions(+), 77 deletions(-)

diff --git a/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java b/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java
index accb23f799..c1c0c14235 100644
--- a/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java
+++ b/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java
@@ -94,7 +94,6 @@ public class AuxiliaryServiceManager {
         });
   }
 
-  @VisibleForTesting
   /**
    * Returns whether the given auxiliary service was configured and registered.
    *
@@ -105,6 +104,7 @@ public class AuxiliaryServiceManager {
     return auxServices.containsKey(auxServiceName);
   }
 
+  @VisibleForTesting
   public IsolatedClassLoader getIsolatedClassLoader(List<String> classPaths) {
     return IsolatedClassLoader.buildClassLoader(classPaths);
   }
diff --git a/core/src/test/java/org/apache/gravitino/auxiliary/TestAuxiliaryServiceManager.java b/core/src/test/java/org/apache/gravitino/auxiliary/TestAuxiliaryServiceManager.java
index d5ff499fc8..5df4b897f2 100644
--- a/core/src/test/java/org/apache/gravitino/auxiliary/TestAuxiliaryServiceManager.java
+++ b/core/src/test/java/org/apache/gravitino/auxiliary/TestAuxiliaryServiceManager.java
@@ -112,6 +112,33 @@ public class TestAuxiliaryServiceManager {
     verify(auxService2, times(1)).serviceStop();
   }
 
+  @Test
+  public void testIsAuxServiceRegistered() throws Exception {
+    GravitinoAuxiliaryService auxService = mock(GravitinoAuxiliaryService.class);
+    IsolatedClassLoader isolatedClassLoader =
+        new IsolatedClassLoader(
+            Collections.emptyList(), Collections.emptyList(), Collections.emptyList());
+
+    AuxiliaryServiceManager auxServiceManager = new AuxiliaryServiceManager();
+    AuxiliaryServiceManager spyAuxManager = spy(auxServiceManager);
+    doReturn(isolatedClassLoader).when(spyAuxManager).getIsolatedClassLoader(anyList());
+    doReturn(auxService).when(spyAuxManager).loadAuxService("iceberg-rest", isolatedClassLoader);
+
+    Assertions.assertFalse(spyAuxManager.isAuxServiceRegistered("iceberg-rest"));
+
+    spyAuxManager.serviceInit(
+        DummyConfig.of(
+            ImmutableMap.of(
+                AuxiliaryServiceManager.GRAVITINO_AUX_SERVICE_PREFIX
+                    + AuxiliaryServiceManager.AUX_SERVICE_NAMES,
+                "iceberg-rest",
+                "gravitino.iceberg-rest." + AuxiliaryServiceManager.AUX_SERVICE_CLASSPATH,
+                "/tmp")));
+
+    Assertions.assertTrue(spyAuxManager.isAuxServiceRegistered("iceberg-rest"));
+    Assertions.assertFalse(spyAuxManager.isAuxServiceRegistered("lance-rest"));
+  }
+
   @Test
   void testAuxiliaryServiceConfigs() {
     Map<String, String> m =
diff --git a/docs/trino-connector/catalog-iceberg.md b/docs/trino-connector/catalog-iceberg.md
index 02779e8041..5a214fc624 100644
--- a/docs/trino-connector/catalog-iceberg.md
+++ b/docs/trino-connector/catalog-iceberg.md
@@ -34,16 +34,25 @@ IRC means every table access gets a freshly issued temporary credential over the
 protocol.
 
 The connector already connects to the Gravitino server (it is how catalogs are discovered in the
-first place), so it also asks that server whether it has an Iceberg REST server running for the
-connector's metalake, and uses the endpoint the server reports. Nothing needs to be configured for
-this: `etc/catalog/gravitino.properties` only needs the usual `gravitino.uri` and
-`gravitino.metalake`. If the server reports no endpoint — the IRC is not running, or it serves a
-different metalake — `lakehouse-iceberg` catalogs fall back to translating `catalog-backend` as
-before, and credential vending does not work.
-
-Set `gravitino.iceberg.rest-uri` only to override the discovered endpoint, for example when the IRC
-is not reachable at the address the Gravitino server itself reports (a split network, or the IRC
-deployed independently of the main server):
+first place), so it also asks that server whether it has an Iceberg REST server running as an
+[auxiliary service](../iceberg-rest-service.md) for the connector's metalake, and uses the endpoint
+the server reports. Nothing needs to be configured for this: `etc/catalog/gravitino.properties` only
+needs the usual `gravitino.uri` and `gravitino.metalake`. If the server reports no endpoint — the
+IRC is not running as an auxiliary service, or it serves a different metalake — `lakehouse-iceberg`
+catalogs fall back to translating `catalog-backend` as before, and credential vending does not work.
+
+Only the coordinator polls the Gravitino server, so the coordinator resolves the endpoint once, when
+a catalog is first registered or reloaded, and hands it to every node (coordinator and workers alike)
+as part of that catalog's own definition — the same way Trino replicates any other catalog property
+cluster-wide. A practical consequence: a catalog registered before the IRC started keeps its existing
+routing until Gravitino reports a change *and* the catalog itself is reloaded (its metadata changes,
+or Trino restarts) — starting the IRC alone does not retroactively re-route an already-registered
+catalog.
+
+Set `gravitino.iceberg.rest-uri` to override the discovered endpoint, and it is required — not just
+an override — for a standalone IRC (its own process, not the Gravitino server's auxiliary service):
+the Gravitino server has no way to know a standalone IRC exists, so discovery never finds one. See
+[Limitations](#limitations).
 
 ```properties
 connector.name=gravitino
@@ -120,6 +129,12 @@ keeping per-user credential vending and per-user authorization intact. Set
 - A deployment that does not run the IRC needs no configuration at all: the server reports no
   endpoint, and `lakehouse-iceberg` catalogs are translated into Trino's `jdbc` or `hive_metastore`
   catalog types as before.
+- Discovery only works for an IRC running as a Gravitino auxiliary service
+  (`gravitino.auxService.names=iceberg-rest`), embedded in the same process as the Gravitino server.
+  A standalone IRC — its own process, started with `GravitinoIcebergRESTServer` and its own
+  `gravitino-iceberg-rest-server.conf` — never registers with the Gravitino server, so the server
+  has no way to know it exists; the Gravitino server reports no endpoint even while a standalone IRC
+  is running. Set `gravitino.iceberg.rest-uri` manually in this case.
 
 ## Schema Operations
 
diff --git a/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java b/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java
index 0ea698a6a4..f296e068db 100644
--- a/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java
+++ b/server/src/main/java/org/apache/gravitino/server/web/rest/IcebergRESTServiceOperations.java
@@ -32,9 +32,9 @@ import javax.ws.rs.core.Response;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.gravitino.Config;
 import org.apache.gravitino.GravitinoEnv;
+import org.apache.gravitino.auxiliary.AuxiliaryServiceManager;
 import org.apache.gravitino.dto.responses.IcebergRESTServiceResponse;
 import org.apache.gravitino.metrics.MetricNames;
-import org.apache.gravitino.server.web.JettyServerConfig;
 import org.apache.gravitino.server.web.Utils;
 
 /**
@@ -52,6 +52,17 @@ public class IcebergRESTServiceOperations {
   // The post-strip key used by the Iceberg REST server itself; see
   // IcebergConstants.GRAVITINO_METALAKE and DynamicIcebergConfigProvider.
   private static final String SERVED_METALAKE_KEY = CONFIG_PREFIX + "gravitino-metalake";
+  private static final String HOST_KEY = CONFIG_PREFIX + "host";
+  private static final String HTTP_PORT_KEY = CONFIG_PREFIX + "httpPort";
+  private static final String HTTPS_PORT_KEY = CONFIG_PREFIX + "httpsPort";
+  private static final String ENABLE_HTTPS_KEY = CONFIG_PREFIX + "enableHttps";
+  // Match IcebergConfig.DEFAULT_ICEBERG_REST_SERVICE_HTTP_PORT/HTTPS_PORT: the server module
+  // cannot depend on iceberg-common, and JettyServerConfig's own defaults are the Gravitino
+  // server's (8090/8433), not the Iceberg REST server's — reading raw values with these
+  // defaults avoids silently reporting the wrong port when httpPort is not set explicitly.
+  private static final int DEFAULT_HTTP_PORT = 9001;
+  private static final int DEFAULT_HTTPS_PORT = 9433;
+  private static final String DEFAULT_HOST = "0.0.0.0";
 
   @Context private HttpServletRequest httpRequest;
 
@@ -67,15 +78,33 @@ public class IcebergRESTServiceOperations {
   @Timed(name = "iceberg-rest-service." + MetricNames.HTTP_PROCESS_DURATION, absolute = true)
   @ResponseMetered(name = "iceberg-rest-service", absolute = true)
   public Response getIcebergRestServiceUri(@QueryParam("metalake") String metalake) {
-    return Utils.ok(new IcebergRESTServiceResponse(resolveUri(metalake)));
+    // The reported host can depend on the caller's own Host header (see resolveUri), so this
+    // response must never be cached and replayed to a different caller.
+    return Response.fromResponse(Utils.ok(new IcebergRESTServiceResponse(resolveUri(metalake))))
+        .header("Cache-Control", "no-store")
+        .build();
+  }
+
+  // Overridable so tests can inject a fixture without bootstrapping GravitinoEnv, matching
+  // HealthOperations's testing pattern.
+  AuxiliaryServiceManager getAuxServiceManager() {
+    return GravitinoEnv.getInstance().auxServiceManager();
+  }
+
+  Config getConfig() {
+    return GravitinoEnv.getInstance().config();
+  }
+
+  HttpServletRequest getHttpRequest() {
+    return httpRequest;
   }
 
   private String resolveUri(String metalake) {
-    if (!GravitinoEnv.getInstance().auxServiceManager().isAuxServiceRegistered(AUX_SERVICE_NAME)) {
+    if (!getAuxServiceManager().isAuxServiceRegistered(AUX_SERVICE_NAME)) {
       return null;
     }
 
-    Config config = GravitinoEnv.getInstance().config();
+    Config config = getConfig();
     String servedMetalake = config.getRawString(SERVED_METALAKE_KEY, "");
     if (StringUtils.isNotBlank(metalake)
         && StringUtils.isNotBlank(servedMetalake)
@@ -85,21 +114,42 @@ public class IcebergRESTServiceOperations {
       return null;
     }
 
-    JettyServerConfig icebergRestConfig = JettyServerConfig.fromConfig(config, CONFIG_PREFIX);
-    String host = icebergRestConfig.getHost();
+    String host = config.getRawString(HOST_KEY, DEFAULT_HOST);
     if (isWildcardHost(host)) {
       // The Iceberg REST server binds to all interfaces, so it has no single externally
       // reachable address of its own. The caller already reached this Gravitino server at some
       // resolvable host, so reuse it — this holds whenever both services share a host, which is
       // the common case, and callers with a genuinely split topology can still set
       // gravitino.iceberg.rest-uri manually.
-      host = httpRequest.getServerName();
+      host = getHttpRequest().getServerName();
+    }
+    boolean enableHttps = Boolean.parseBoolean(config.getRawString(ENABLE_HTTPS_KEY, "false"));
+    String scheme = enableHttps ? "https" : "http";
+    int port =
+        parsePort(
+            config,
+            enableHttps ? HTTPS_PORT_KEY : HTTP_PORT_KEY,
+            enableHttps ? DEFAULT_HTTPS_PORT : DEFAULT_HTTP_PORT);
+    return String.format("%s://%s:%d/iceberg", scheme, host, port);
+  }
+
+  private static int parsePort(Config config, String key, int defaultPort) {
+    String value = config.getRawString(key, "");
+    if (StringUtils.isBlank(value)) {
+      return defaultPort;
+    }
+    try {
+      return Integer.parseInt(value.trim());
+    } catch (NumberFormatException e) {
+      return defaultPort;
     }
-    String scheme = icebergRestConfig.isEnableHttps() ? "https" : "http";
-    return String.format("%s://%s:%d/iceberg", scheme, host, icebergRestConfig.getHttpPort());
   }
 
   private static boolean isWildcardHost(String host) {
-    return StringUtils.isBlank(host) || "0.0.0.0".equals(host) || "::".equals(host);
+    return StringUtils.isBlank(host)
+        || "0.0.0.0".equals(host)
+        || "::".equals(host)
+        || "[::]".equals(host)
+        || "0:0:0:0:0:0:0:0".equals(host);
   }
 }
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java
new file mode 100644
index 0000000000..d295f75ada
--- /dev/null
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java
@@ -0,0 +1,174 @@
+/*
+ * 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.web.rest;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.common.collect.ImmutableMap;
+import java.util.Map;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.Response;
+import org.apache.gravitino.Config;
+import org.apache.gravitino.auxiliary.AuxiliaryServiceManager;
+import org.apache.gravitino.dto.responses.IcebergRESTServiceResponse;
+import org.junit.jupiter.api.Test;
+
+public class TestIcebergRESTServiceOperations {
+
+  private static class DummyConfig extends Config {
+    static DummyConfig of(Map<String, String> m) {
+      DummyConfig config = new DummyConfig();
+      config.loadFromMap(m, k -> true);
+      return config;
+    }
+  }
+
+  private IcebergRESTServiceOperations newOps(
+      boolean registered, Map<String, String> icebergConfig, String requestServerName) {
+    AuxiliaryServiceManager auxServiceManager = mock(AuxiliaryServiceManager.class);
+    when(auxServiceManager.isAuxServiceRegistered("iceberg-rest")).thenReturn(registered);
+    Config config = DummyConfig.of(icebergConfig);
+    HttpServletRequest request = mock(HttpServletRequest.class);
+    when(request.getServerName()).thenReturn(requestServerName);
+
+    return new IcebergRESTServiceOperations() {
+      @Override
+      AuxiliaryServiceManager getAuxServiceManager() {
+        return auxServiceManager;
+      }
+
+      @Override
+      Config getConfig() {
+        return config;
+      }
+
+      @Override
+      HttpServletRequest getHttpRequest() {
+        return request;
+      }
+    };
+  }
+
+  private String uriOf(Response response) {
+    return ((IcebergRESTServiceResponse) response.getEntity()).getUri();
+  }
+
+  @Test
+  public void testReturnsNullWhenAuxServiceNotRegistered() {
+    IcebergRESTServiceOperations ops = newOps(false, ImmutableMap.of(), "gravitino-host");
+    assertNull(uriOf(ops.getIcebergRestServiceUri("test")));
+  }
+
+  @Test
+  public void testDefaultPortIsTheIcebergRestDefaultNotTheGravitinoServerDefault() {
+    // Regression test: without an explicit gravitino.iceberg-rest.httpPort, the reported port
+    // must be the Iceberg REST server's own default (9001), not the Gravitino webserver's
+    // default (8090) that JettyServerConfig would otherwise fall back to.
+    IcebergRESTServiceOperations ops =
+        newOps(true, ImmutableMap.of("gravitino.iceberg-rest.host", "irc-host"), "gravitino-host");
+    assertEquals("http://irc-host:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));
+  }
+
+  @Test
+  public void testHttpsUsesTheHttpsPortNotTheHttpPort() {
+    IcebergRESTServiceOperations ops =
+        newOps(
+            true,
+            ImmutableMap.of(
+                "gravitino.iceberg-rest.host", "irc-host",
+                "gravitino.iceberg-rest.enableHttps", "true"),
+            "gravitino-host");
+    assertEquals("https://irc-host:9433/iceberg", uriOf(ops.getIcebergRestServiceUri("")));
+  }
+
+  @Test
+  public void testExplicitPortIsHonored() {
+    IcebergRESTServiceOperations ops =
+        newOps(
+            true,
+            ImmutableMap.of(
+                "gravitino.iceberg-rest.host", "irc-host",
+                "gravitino.iceberg-rest.httpPort", "19001"),
+            "gravitino-host");
+    assertEquals("http://irc-host:19001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));
+  }
+
+  @Test
+  public void testWildcardHostFallsBackToRequestServerName() {
+    IcebergRESTServiceOperations ops =
+        newOps(
+            true,
+            ImmutableMap.of("gravitino.iceberg-rest.host", "0.0.0.0"),
+            "host.docker.internal");
+    assertEquals(
+        "http://host.docker.internal:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));
+  }
+
+  @Test
+  public void testBlankHostIsTreatedAsWildcard() {
+    IcebergRESTServiceOperations ops = newOps(true, ImmutableMap.of(), "gravitino-host");
+    assertEquals("http://gravitino-host:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));
+  }
+
+  @Test
+  public void testMismatchedMetalakeReturnsNull() {
+    IcebergRESTServiceOperations ops =
+        newOps(
+            true,
+            ImmutableMap.of(
+                "gravitino.iceberg-rest.host", "irc-host",
+                "gravitino.iceberg-rest.gravitino-metalake", "prod"),
+            "gravitino-host");
+    assertNull(uriOf(ops.getIcebergRestServiceUri("test")));
+  }
+
+  @Test
+  public void testMatchingMetalakeIsReported() {
+    IcebergRESTServiceOperations ops =
+        newOps(
+            true,
+            ImmutableMap.of(
+                "gravitino.iceberg-rest.host", "irc-host",
+                "gravitino.iceberg-rest.gravitino-metalake", "test"),
+            "gravitino-host");
+    assertEquals("http://irc-host:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("test")));
+  }
+
+  @Test
+  public void testBlankRequestedMetalakeSkipsTheMetalakeCheck() {
+    IcebergRESTServiceOperations ops =
+        newOps(
+            true,
+            ImmutableMap.of(
+                "gravitino.iceberg-rest.host", "irc-host",
+                "gravitino.iceberg-rest.gravitino-metalake", "prod"),
+            "gravitino-host");
+    assertEquals("http://irc-host:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));
+  }
+
+  @Test
+  public void testResponseIsNotCacheable() {
+    IcebergRESTServiceOperations ops = newOps(true, ImmutableMap.of(), "gravitino-host");
+    Response response = ops.getIcebergRestServiceUri("");
+    assertEquals("no-store", response.getHeaderString("Cache-Control"));
+  }
+}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
index 2c1f795afb..b86fa5c5dc 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
@@ -710,9 +710,12 @@ public class GravitinoConfig {
 
   /**
    * Sets the Iceberg REST server endpoint discovered from the Gravitino server for the given
-   * metalake. Called by the catalog connector manager's periodic metalake poll; ignored for a
-   * metalake where {@code gravitino.iceberg.rest-uri} is explicitly configured, which always takes
-   * precedence.
+   * metalake. Called only by the catalog connector manager's periodic metalake poll, which runs on
+   * the coordinator only — {@link #getDiscoveredIcebergRestUri} is therefore not by itself a valid
+   * routing signal on a worker node. The coordinator is responsible for embedding the discovered
+   * value into each catalog's own properties at registration time, so that it travels to every node
+   * through the {@code CREATE CATALOG} statement Trino replicates cluster-wide; see {@code
+   * CatalogRegister.generateCreateCatalogCommand}.
    *
    * @param metalake the metalake the endpoint was discovered for
    * @param uri the discovered endpoint, or {@code null} when the Iceberg REST server is not running
@@ -727,24 +730,29 @@ public class GravitinoConfig {
   }
 
   /**
-   * Retrieves the Iceberg REST server endpoint to route the given metalake's lakehouse-iceberg
-   * catalogs through. Prefers an explicitly configured {@code gravitino.iceberg.rest-uri};
-   * otherwise falls back to the endpoint discovered from the Gravitino server for this metalake, if
-   * any.
+   * Retrieves the Iceberg REST server endpoint discovered from the Gravitino server for the given
+   * metalake, with no fallback to the manually configured endpoint. Only valid on the node that
+   * runs the periodic discovery poll (the coordinator); see {@link #setDiscoveredIcebergRestUri}.
    *
    * @param metalake the metalake to resolve the endpoint for
-   * @return the Iceberg REST server endpoint, or an empty string when none is available
+   * @return the discovered endpoint, or an empty string when none is available
    */
-  public String getIcebergRestUri(String metalake) {
-    String configured =
-        config.getOrDefault(
-            GRAVITINO_ICEBERG_REST_URI.key, GRAVITINO_ICEBERG_REST_URI.defaultValue);
-    if (StringUtils.isNotBlank(configured)) {
-      return configured;
-    }
+  public String getDiscoveredIcebergRestUri(String metalake) {
     return discoveredIcebergRestUriByMetalake.getOrDefault(metalake, "");
   }
 
+  /**
+   * Retrieves the manually configured {@code gravitino.iceberg.rest-uri}, if any. Unlike the
+   * discovered endpoint, this is plain local file configuration and is therefore identical and
+   * valid on every node — coordinator and workers alike.
+   *
+   * @return the manually configured Iceberg REST server endpoint, or an empty string when unset
+   */
+  public String getManualIcebergRestUri() {
+    return config.getOrDefault(
+        GRAVITINO_ICEBERG_REST_URI.key, GRAVITINO_ICEBERG_REST_URI.defaultValue);
+  }
+
   /**
    * Retrieves the properties passed through to the internal Trino Iceberg REST catalog, with the
    * {@code gravitino.iceberg.rest-catalog.} prefix rewritten to {@code iceberg.rest-catalog.}.
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
index faca9c2499..35f722bb1e 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
@@ -38,6 +38,7 @@ import java.util.Set;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.gravitino.trino.connector.GravitinoConfig;
 import org.apache.gravitino.trino.connector.GravitinoErrorCode;
+import org.apache.gravitino.trino.connector.catalog.iceberg.IcebergConnectorAdapter;
 import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
@@ -304,12 +305,18 @@ public class CatalogRegister {
 
   private String generateCreateCatalogCommand(String name, GravitinoCatalog gravitinoCatalog)
       throws Exception {
+    // This statement is replicated by Trino to every node in the cluster, coordinator and workers
+    // alike, so it is the only place a value the coordinator alone knows (like the Iceberg REST
+    // server endpoint it discovered) can reach every node that will build this catalog's internal
+    // connector config.
+    GravitinoCatalog catalogToRegister =
+        IcebergConnectorAdapter.embedDiscoveredIcebergRestUri(gravitinoCatalog, config);
     return String.format(
         "CREATE CATALOG %s USING gravitino WITH ( \"%s\" = 'true', \"%s\" = '%s', %s)",
         name,
         GRAVITINO_DYNAMIC_CONNECTOR,
         GRAVITINO_DYNAMIC_CONNECTOR_CATALOG_CONFIG,
-        GravitinoCatalog.toJson(gravitinoCatalog),
+        GravitinoCatalog.toJson(catalogToRegister),
         config.toCatalogConfig());
   }
 
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
index 5d81fd02ab..14aed17709 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
@@ -149,14 +149,14 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
    * the backend path by {@link #applyCredentials}.
    *
    * @param catalog the Gravitino catalog to load
-   * @param gravitinoConfig the connector configuration holding the Iceberg REST server endpoint
+   * @param gravitinoConfig the connector configuration holding the Iceberg REST catalog's
+   *     authentication and other pass-through settings
+   * @param restUri the Iceberg REST server endpoint to route through, resolved by the caller
    * @return the Trino Iceberg connector config
-   * @throws TrinoException if no Iceberg REST server endpoint is configured or discovered for this
-   *     catalog's metalake
+   * @throws TrinoException if {@code restUri} is blank
    */
   public Map<String, String> buildIcebergRestProperties(
-      GravitinoCatalog catalog, GravitinoConfig gravitinoConfig) {
-    String restUri = gravitinoConfig.getIcebergRestUri(catalog.getMetalake());
+      GravitinoCatalog catalog, GravitinoConfig gravitinoConfig, String restUri) {
     if (StringUtils.isBlank(restUri)) {
       // The caller only reaches this method once it has already confirmed a non-blank URI, so
       // this is defensive: it can only fire if that URI disappeared between the two calls.
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java
index 4cdd9cd1c0..85df20d944 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.trino.connector.catalog.iceberg;
 
 import static java.util.Collections.emptyList;
 
+import com.google.common.collect.ImmutableMap;
 import io.trino.spi.session.PropertyMetadata;
 import java.util.HashMap;
 import java.util.List;
@@ -44,6 +45,18 @@ public class IcebergConnectorAdapter implements CatalogConnectorAdapter {
 
   private static final String CONNECTOR_ICEBERG = "iceberg";
   private static final String REST_CATALOG_BACKEND = "rest";
+  private static final String ICEBERG_PROVIDER = "lakehouse-iceberg";
+
+  /**
+   * Synthetic catalog property carrying the Iceberg REST server endpoint the coordinator discovered
+   * for this catalog's metalake. {@link GravitinoConfig}'s own discovered-endpoint map is populated
+   * only on the coordinator (the periodic discovery poll never runs on a worker), so it cannot be
+   * read directly when building a catalog's internal connector config: every node needs the same
+   * routing decision for the same catalog. Embedding the resolved endpoint into the catalog itself,
+   * at registration time, means it travels to every node through the {@code CREATE CATALOG}
+   * statement Trino replicates cluster-wide, the same way any other catalog property does.
+   */
+  static final String DISCOVERED_ICEBERG_REST_URI_PROPERTY = "__gravitino.iceberg.rest-uri";
 
   private final IcebergPropertyMeta propertyMetadata;
   private final IcebergCatalogPropertyConverter catalogConverter;
@@ -65,12 +78,21 @@ public class IcebergConnectorAdapter implements CatalogConnectorAdapter {
   public Map<String, String> buildInternalConnectorConfig(
       GravitinoCatalog catalog, Credential[] credentials) throws Exception {
     // The catalog backend describes how Gravitino stores the metadata; it does not decide how
-    // Trino reaches the data. Whenever the Gravitino server reports a running Iceberg REST
-    // server for this catalog's metalake, the catalog is loaded through it, the only path that
-    // supports temporary credentials. A catalog that already has a REST backend keeps pointing at
-    // its own configured endpoint. If the server reports nothing, this falls back to translating
-    // catalog-backend as before — nothing to configure either way.
-    if (StringUtils.isNotBlank(config.getIcebergRestUri(catalog.getMetalake()))
+    // Trino reaches the data. Whenever an Iceberg REST server endpoint is available for this
+    // catalog's metalake, the catalog is loaded through it, the only path that supports temporary
+    // credentials. A catalog that already has a REST backend keeps pointing at its own configured
+    // endpoint. If no endpoint is available, this falls back to translating catalog-backend as
+    // before — nothing to configure either way.
+    //
+    // The manual override is plain local config, so it is valid on every node as-is. The
+    // discovered endpoint is coordinator-only knowledge, so it is read from the catalog's own
+    // properties, where the coordinator embeds it at registration time (see
+    // embedDiscoveredIcebergRestUri), rather than from GravitinoConfig directly.
+    String restUri = config.getManualIcebergRestUri();
+    if (StringUtils.isBlank(restUri)) {
+      restUri = catalog.getProperty(DISCOVERED_ICEBERG_REST_URI_PROPERTY, "");
+    }
+    if (StringUtils.isNotBlank(restUri)
         && !REST_CATALOG_BACKEND.equalsIgnoreCase(
             catalog.getProperty(IcebergConstants.CATALOG_BACKEND, null))) {
       // `credentials` is intentionally unused here: with vended credentials enabled, Trino obtains
@@ -81,7 +103,7 @@ public class IcebergConnectorAdapter implements CatalogConnectorAdapter {
               + " are not applied because the REST protocol vends one per table access.",
           catalog.getName(),
           credentials.length);
-      return catalogConverter.buildIcebergRestProperties(catalog, config);
+      return catalogConverter.buildIcebergRestProperties(catalog, config, restUri);
     }
 
     Map<String, String> connectorConfig =
@@ -90,6 +112,41 @@ public class IcebergConnectorAdapter implements CatalogConnectorAdapter {
     return connectorConfig;
   }
 
+  /**
+   * Returns a copy of {@code catalog} with the Iceberg REST server endpoint the coordinator
+   * discovered for its metalake embedded as a synthetic property, if the catalog is a
+   * lakehouse-iceberg catalog and a discovered endpoint exists. Called only on the coordinator,
+   * before a catalog is registered with Trino, so that the routing decision reaches every node
+   * through the {@code CREATE CATALOG} statement — see {@link
+   * #DISCOVERED_ICEBERG_REST_URI_PROPERTY}.
+   *
+   * @param catalog the catalog about to be registered
+   * @param config the connector configuration holding the discovered endpoints
+   * @return {@code catalog} unchanged if it is not a lakehouse-iceberg catalog or no endpoint was
+   *     discovered for its metalake; otherwise a copy with the endpoint embedded
+   */
+  public static GravitinoCatalog embedDiscoveredIcebergRestUri(
+      GravitinoCatalog catalog, GravitinoConfig config) {
+    if (!ICEBERG_PROVIDER.equals(catalog.getProvider())) {
+      return catalog;
+    }
+    String discoveredUri = config.getDiscoveredIcebergRestUri(catalog.getMetalake());
+    if (StringUtils.isBlank(discoveredUri)) {
+      return catalog;
+    }
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .putAll(catalog.getProperties())
+            .put(DISCOVERED_ICEBERG_REST_URI_PROPERTY, discoveredUri)
+            .buildKeepingLast();
+    return new GravitinoCatalog(
+        catalog.getMetalake(),
+        catalog.getProvider(),
+        catalog.getName(),
+        properties,
+        catalog.getLastModifiedTime());
+  }
+
   @Override
   public String internalConnectorName() {
     return CONNECTOR_ICEBERG;
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
index 0528006823..5d03d2e507 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
@@ -305,7 +305,8 @@ public class TestGravitinoConfig {
     GravitinoConfig config = new GravitinoConfig(ImmutableMap.of("gravitino.metalake", "user_001"));
 
     // Nothing configured, and nothing discovered yet.
-    assertEquals("", config.getIcebergRestUri("user_001"));
+    assertEquals("", config.getManualIcebergRestUri());
+    assertEquals("", config.getDiscoveredIcebergRestUri("user_001"));
     assertTrue(config.getIcebergRestCatalogConfig().isEmpty());
   }
 
@@ -323,9 +324,8 @@ public class TestGravitinoConfig {
             "client_id:client_secret");
     GravitinoConfig config = new GravitinoConfig(configMap);
 
-    // A manually configured URI applies regardless of metalake.
-    assertEquals("http://127.0.0.1:9001/iceberg", config.getIcebergRestUri("user_001"));
-    assertEquals("http://127.0.0.1:9001/iceberg", config.getIcebergRestUri("other_metalake"));
+    // A manually configured URI is plain local config, not scoped to any metalake.
+    assertEquals("http://127.0.0.1:9001/iceberg", config.getManualIcebergRestUri());
 
     Map<String, String> restCatalogConfig = config.getIcebergRestCatalogConfig();
     assertEquals(2, restCatalogConfig.size());
@@ -341,29 +341,14 @@ public class TestGravitinoConfig {
     config.setDiscoveredIcebergRestUri("metalake_a", "http://irc-a:9001/iceberg");
     config.setDiscoveredIcebergRestUri("metalake_b", "http://irc-b:9001/iceberg");
 
-    assertEquals("http://irc-a:9001/iceberg", config.getIcebergRestUri("metalake_a"));
-    assertEquals("http://irc-b:9001/iceberg", config.getIcebergRestUri("metalake_b"));
+    assertEquals("http://irc-a:9001/iceberg", config.getDiscoveredIcebergRestUri("metalake_a"));
+    assertEquals("http://irc-b:9001/iceberg", config.getDiscoveredIcebergRestUri("metalake_b"));
     // Unknown/unmatched metalakes fall back to nothing.
-    assertEquals("", config.getIcebergRestUri("metalake_c"));
+    assertEquals("", config.getDiscoveredIcebergRestUri("metalake_c"));
 
     // Clearing (e.g. the server stopped reporting an endpoint) removes it again.
     config.setDiscoveredIcebergRestUri("metalake_a", null);
-    assertEquals("", config.getIcebergRestUri("metalake_a"));
-  }
-
-  @Test
-  public void testManualIcebergRestUriOverridesDiscovery() {
-    GravitinoConfig config =
-        new GravitinoConfig(
-            ImmutableMap.of(
-                "gravitino.metalake",
-                "user_001",
-                "gravitino.iceberg.rest-uri",
-                "http://manual:9001/iceberg"));
-
-    config.setDiscoveredIcebergRestUri("user_001", "http://discovered:9001/iceberg");
-
-    assertEquals("http://manual:9001/iceberg", config.getIcebergRestUri("user_001"));
+    assertEquals("", config.getDiscoveredIcebergRestUri("metalake_a"));
   }
 
   @Test
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
index 8ad738188f..ee3e448c29 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
@@ -353,7 +353,7 @@ public class TestIcebergCatalogPropertyConverter {
 
     Assertions.assertThrows(
         TrinoException.class,
-        () -> converter.buildIcebergRestProperties(catalog, icebergRestUnavailableConfig()));
+        () -> converter.buildIcebergRestProperties(catalog, icebergRestUnavailableConfig(), ""));
   }
 
   @Test
@@ -366,12 +366,15 @@ public class TestIcebergCatalogPropertyConverter {
             .build();
 
     // No manual gravitino.iceberg.rest-uri: only a per-metalake value discovered from the
-    // Gravitino server, exactly as CatalogConnectorManager's periodic poll would set it.
+    // Gravitino server, embedded onto the catalog exactly as CatalogRegister does before
+    // registering it — this is the only way a worker (which never runs discovery itself) can see
+    // the same routing decision as the coordinator.
     Map<String, String> config =
         buildConnectorConfig(
             "catalog1",
             properties,
-            icebergRestDiscoveredConfig("test", "http://discovered:9001/iceberg"));
+            icebergRestDiscoveredConfig("test", "http://discovered:9001/iceberg"),
+            /* embedDiscovery= */ true);
 
     Assertions.assertEquals("rest", config.get("iceberg.catalog.type"));
     Assertions.assertEquals(
@@ -388,12 +391,36 @@ public class TestIcebergCatalogPropertyConverter {
             .build();
 
     // Discovery reported an endpoint for a different metalake than the one this catalog belongs
-    // to (the mock catalog's metalake is "test"); it must not leak across metalakes.
+    // to (the mock catalog's metalake is "test"); embedDiscoveredIcebergRestUri must not embed it.
     Map<String, String> config =
         buildConnectorConfig(
             "catalog1",
             properties,
-            icebergRestDiscoveredConfig("other_metalake", "http://other:9001/iceberg"));
+            icebergRestDiscoveredConfig("other_metalake", "http://other:9001/iceberg"),
+            /* embedDiscovery= */ true);
+
+    Assertions.assertEquals("jdbc", config.get("iceberg.catalog.type"));
+    Assertions.assertNull(config.get("iceberg.rest-catalog.uri"));
+  }
+
+  @Test
+  public void testDiscoveredUriUnusedWithoutEmbedding() throws Exception {
+    // A worker never runs discovery, so its own GravitinoConfig never has a discovered value
+    // populated — this asserts that IcebergConnectorAdapter really does read the routing signal
+    // from the catalog, not from GravitinoConfig's discovered map directly.
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .put("catalog-backend", "jdbc")
+            .put("uri", "jdbc:postgresql://localhost:5432/iceberg")
+            .put("jdbc-driver", "org.postgresql.Driver")
+            .build();
+
+    Map<String, String> config =
+        buildConnectorConfig(
+            "catalog1",
+            properties,
+            icebergRestDiscoveredConfig("test", "http://discovered:9001/iceberg"),
+            /* embedDiscovery= */ false);
 
     Assertions.assertEquals("jdbc", config.get("iceberg.catalog.type"));
     Assertions.assertNull(config.get("iceberg.rest-catalog.uri"));
@@ -692,6 +719,30 @@ public class TestIcebergCatalogPropertyConverter {
         .buildInternalConnectorConfig(new GravitinoCatalog("test", mockCatalog), credentials);
   }
 
+  /**
+   * Like {@link #buildConnectorConfig(String, Map, GravitinoConfig, Credential[])}, but for
+   * discovered-endpoint scenarios: {@code embedDiscovery} mirrors what {@code CatalogRegister} does
+   * before registering a catalog, so a discovered value only reaches the adapter the same way it
+   * would on a real node — through the catalog, never by reading {@code GravitinoConfig}'s
+   * discovered map directly.
+   */
+  private static Map<String, String> buildConnectorConfig(
+      String catalogName,
+      Map<String, String> properties,
+      GravitinoConfig gravitinoConfig,
+      boolean embedDiscovery)
+      throws Exception {
+    Catalog mockCatalog =
+        TestGravitinoCatalog.mockCatalog(
+            catalogName, "lakehouse-iceberg", "test catalog", Catalog.Type.RELATIONAL, properties);
+    GravitinoCatalog catalog = new GravitinoCatalog("test", mockCatalog);
+    if (embedDiscovery) {
+      catalog = IcebergConnectorAdapter.embedDiscoveredIcebergRestUri(catalog, gravitinoConfig);
+    }
+    return new IcebergConnectorAdapter(gravitinoConfig)
+        .buildInternalConnectorConfig(catalog, new Credential[0]);
+  }
+
   private static GravitinoConfig icebergRestUnavailableConfig() {
     // No manual gravitino.iceberg.rest-uri, and nothing discovered for this metalake: the
     // connector has no endpoint to route through, so catalogs fall back to their own backend.


(gravitino) 02/13: [Cherry-pick to branch-1.3] [#12526] feat(trino-connector): Support Starburst SPI compatibility (#12527)

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diqiu50 pushed a commit to branch trino-irc-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit fb42cd6b993bea466eb8725f4ccadffd8f225a45
Author: Yuhui <hu...@datastrato.com>
AuthorDate: Fri Aug 21 10:02:07 2026 +0800

    [Cherry-pick to branch-1.3] [#12526] feat(trino-connector): Support Starburst SPI compatibility (#12527)
---
 .../trino/connector/GravitinoConnectorFactory.java |  48 +++++++-
 .../trino/connector/GravitinoDynamicFilter.java    |  16 +++
 .../trino/connector/util/json/JsonCodec.java       | 123 ++++++++++++++++++++-
 .../connector/TestGravitinoConnectorFactory.java   |  74 +++++++++++++
 .../trino/connector/util/json/TestJsonCodec.java   | 105 ++++++++++++++++++
 5 files changed, 362 insertions(+), 4 deletions(-)

diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java
index 1420a60c23..5315342713 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java
@@ -19,6 +19,7 @@
 package org.apache.gravitino.trino.connector;
 
 import static io.trino.spi.StandardErrorCode.NOT_SUPPORTED;
+import static org.apache.gravitino.trino.connector.GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT;
 import static org.apache.gravitino.trino.connector.GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR;
 
 import com.google.common.annotations.VisibleForTesting;
@@ -28,7 +29,12 @@ import io.trino.spi.TrinoException;
 import io.trino.spi.connector.Connector;
 import io.trino.spi.connector.ConnectorContext;
 import io.trino.spi.connector.ConnectorFactory;
+import java.util.Locale;
 import java.util.Map;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
 import org.apache.commons.lang3.StringUtils;
 import org.apache.gravitino.client.GravitinoAdminClient;
 import org.apache.gravitino.trino.connector.catalog.CatalogConnectorContext;
@@ -48,6 +54,9 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
   private static final Logger LOG = LoggerFactory.getLogger(GravitinoConnectorFactory.class);
   private static final int MIN_SUPPORT_TRINO_SPI_VERSION = 435;
   private static final int MAX_SUPPORT_TRINO_SPI_VERSION = Integer.MAX_VALUE;
+  private static final Pattern TRINO_SPI_VERSION_PATTERN = Pattern.compile("^(\\d+)");
+  private static final Set<String> SECURITY_SENSITIVE_PROPERTY_SUFFIXES =
+      Set.of("password", "secret", "token", "credential", "accesskey", "secretkey", "privatekey");
   /** The default connector name. */
   public static final String DEFAULT_CONNECTOR_NAME = "gravitino";
 
@@ -142,6 +151,17 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
     }
   }
 
+  // Note: this method is not annotated with @Override because it does not exist in the
+  // ConnectorFactory interface of the baseline open-source Trino SPI version this connector
+  // compiles against. Some newer Trino/Starburst SPI versions declare it as an abstract method,
+  // where it is dispatched at runtime by signature, providing cross-version compatibility.
+  public Set<String> getSecuritySensitivePropertyNames(
+      String catalogName, Map<String, String> config, ConnectorContext context) {
+    return config.keySet().stream()
+        .filter(GravitinoConnectorFactory::isSecuritySensitivePropertyName)
+        .collect(Collectors.toUnmodifiableSet());
+  }
+
   protected GravitinoConnector createConnector(CatalogConnectorContext connectorContext) {
     throw new TrinoException(NOT_SUPPORTED, "Should be overridden in subclass");
   }
@@ -157,7 +177,7 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
 
   private void checkTrinoSpiVersion(ConnectorContext context, GravitinoConfig config) {
     String spiVersion = context.getSpiVersion();
-    trinoVersion = Integer.parseInt(spiVersion);
+    trinoVersion = parseTrinoSpiVersion(spiVersion);
 
     // check catalog name with metalake are supported in this trino version
     if (!config.singleMetalakeMode() && !supportCatalogNameWithMetalake()) {
@@ -192,6 +212,32 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
     }
   }
 
+  @VisibleForTesting
+  static boolean isSecuritySensitivePropertyName(String propertyName) {
+    String normalizedPropertyName = propertyName.toLowerCase(Locale.ROOT).replaceAll("[._-]", "");
+    return SECURITY_SENSITIVE_PROPERTY_SUFFIXES.stream().anyMatch(normalizedPropertyName::endsWith);
+  }
+
+  @VisibleForTesting
+  static int parseTrinoSpiVersion(String spiVersion) {
+    Matcher matcher = TRINO_SPI_VERSION_PATTERN.matcher(spiVersion);
+    if (!matcher.find()) {
+      throw new TrinoException(
+          GRAVITINO_ILLEGAL_ARGUMENT,
+          String.format("Invalid Trino SPI version '%s': expected leading digits", spiVersion));
+    }
+
+    try {
+      return Integer.parseInt(matcher.group(1));
+    } catch (NumberFormatException e) {
+      throw new TrinoException(
+          GRAVITINO_ILLEGAL_ARGUMENT,
+          String.format(
+              "Invalid Trino SPI version '%s': numeric version is out of range", spiVersion),
+          e);
+    }
+  }
+
   protected boolean supportCatalogNameWithMetalake() {
     return true;
   }
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoDynamicFilter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoDynamicFilter.java
index bfc4f430e1..da75a1128d 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoDynamicFilter.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoDynamicFilter.java
@@ -21,6 +21,8 @@ package org.apache.gravitino.trino.connector;
 import io.trino.spi.connector.ColumnHandle;
 import io.trino.spi.connector.DynamicFilter;
 import io.trino.spi.predicate.TupleDomain;
+import java.lang.reflect.Method;
+import java.util.OptionalLong;
 import java.util.Set;
 import java.util.concurrent.CompletableFuture;
 import java.util.stream.Collectors;
@@ -55,6 +57,20 @@ class GravitinoDynamicFilter implements DynamicFilter {
     return delegate.isAwaitable();
   }
 
+  // Note: this method is not annotated with @Override because it does not exist in the
+  // DynamicFilter interface of the baseline open-source Trino SPI version this connector compiles
+  // against. It is present in newer Trino/Starburst SPI versions, where it is dispatched at
+  // runtime by signature, providing cross-version compatibility. When the delegate implements the
+  // same method, its value is forwarded so the underlying SPI's timeout preference is preserved.
+  public OptionalLong getPreferredDynamicFilterTimeout() {
+    try {
+      Method method = delegate.getClass().getMethod("getPreferredDynamicFilterTimeout");
+      return (OptionalLong) method.invoke(delegate);
+    } catch (ReflectiveOperationException | RuntimeException e) {
+      return OptionalLong.empty();
+    }
+  }
+
   @Override
   public TupleDomain<ColumnHandle> getCurrentPredicate() {
     return delegate.getCurrentPredicate().transformKeys(GravitinoHandle::unWrap);
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/util/json/JsonCodec.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/util/json/JsonCodec.java
index 0566858223..00de547b70 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/util/json/JsonCodec.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/util/json/JsonCodec.java
@@ -30,6 +30,7 @@ import com.fasterxml.jackson.datatype.guava.GuavaModule;
 import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
 import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
 import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
+import com.google.common.annotations.VisibleForTesting;
 import io.airlift.json.RecordAutoDetectModule;
 import io.trino.spi.TrinoException;
 import io.trino.spi.block.Block;
@@ -47,15 +48,22 @@ import io.trino.spi.type.StandardTypes;
 import io.trino.spi.type.Type;
 import io.trino.spi.type.TypeManager;
 import io.trino.spi.type.TypeSignature;
+import java.lang.reflect.Constructor;
 import java.lang.reflect.Field;
+import java.util.Collections;
+import java.util.Set;
 import java.util.function.Function;
 import org.apache.gravitino.trino.connector.GravitinoConnectorPluginManager;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 /**
  * Utility class for JSON serialization and deserialization in the Gravitino Trino connector.
  * Provides functionality for handling various Trino-specific types and plugin classes.
  */
 public class JsonCodec {
+
+  private static final Logger LOG = LoggerFactory.getLogger(JsonCodec.class);
   private static volatile ObjectMapper mapper;
   private static volatile Type jsonType;
 
@@ -103,14 +111,123 @@ public class JsonCodec {
 
   static BlockEncodingSerde createBlockEncodingSerde(TypeManager typeManager) throws Exception {
     ClassLoader classLoader = typeManager.getClass().getClassLoader();
-    Class blockEncodingManagerClass =
+    Class<?> blockEncodingManagerClass =
         classLoader.loadClass("io.trino.metadata.BlockEncodingManager");
-    Class internalBlockEncodingSerdeClass =
+    Class<?> internalBlockEncodingSerdeClass =
         classLoader.loadClass("io.trino.metadata.InternalBlockEncodingSerde");
+    Object blockEncodingManager =
+        instantiateBlockEncodingManager(blockEncodingManagerClass, classLoader);
     return (BlockEncodingSerde)
         internalBlockEncodingSerdeClass
             .getConstructor(blockEncodingManagerClass, TypeManager.class)
-            .newInstance(blockEncodingManagerClass.getConstructor().newInstance(), typeManager);
+            .newInstance(blockEncodingManager, typeManager);
+  }
+
+  /**
+   * Instantiate BlockEncodingManager across Trino/Starburst variants. OSS Trino exposes a public
+   * no-arg constructor; Starburst replaces it with BlockEncodingManager(FeaturesConfig) (used to
+   * gate type-specific encodings via feature flags). Newer Trino branches additionally publish a
+   * {@code Set<BlockEncoding>} variant for Guice multibindings. We probe each known signature in
+   * order, then fall back to a generic constructor scan that fills unknown reference parameters
+   * with default values as a last-resort compatibility mechanism.
+   */
+  @VisibleForTesting
+  static Object instantiateBlockEncodingManager(
+      Class<?> blockEncodingManagerClass, ClassLoader classLoader) throws Exception {
+    try {
+      Object instance = blockEncodingManagerClass.getConstructor().newInstance();
+      LOG.debug("Instantiated BlockEncodingManager with its public no-argument constructor");
+      return instance;
+    } catch (NoSuchMethodException ignored) {
+      // fall through to parameterized variants
+    }
+
+    try {
+      Class<?> featuresConfigClass = classLoader.loadClass("io.trino.FeaturesConfig");
+      Constructor<?> ctor = blockEncodingManagerClass.getConstructor(featuresConfigClass);
+      Object featuresConfig = featuresConfigClass.getConstructor().newInstance();
+      Object instance = ctor.newInstance(featuresConfig);
+      LOG.debug("Instantiated BlockEncodingManager with FeaturesConfig");
+      return instance;
+    } catch (NoSuchMethodException | ClassNotFoundException ignored) {
+      // fall through
+    }
+
+    try {
+      Constructor<?> setCtor = blockEncodingManagerClass.getConstructor(Set.class);
+      Object instance = setCtor.newInstance(Collections.emptySet());
+      LOG.debug("Instantiated BlockEncodingManager with an empty BlockEncoding set");
+      return instance;
+    } catch (NoSuchMethodException ignored) {
+      // fall through to last-resort scan
+    }
+
+    NoSuchMethodException lastError = null;
+    for (Constructor<?> ctor : blockEncodingManagerClass.getDeclaredConstructors()) {
+      if (!ctor.trySetAccessible()) {
+        continue;
+      }
+
+      Class<?>[] paramTypes = ctor.getParameterTypes();
+      Object[] args = new Object[paramTypes.length];
+      boolean resolvable = true;
+      for (int i = 0; i < paramTypes.length && resolvable; i++) {
+        if (Set.class.isAssignableFrom(paramTypes[i])) {
+          args[i] = Collections.emptySet();
+        } else if (paramTypes[i].isPrimitive()) {
+          args[i] = defaultPrimitive(paramTypes[i]);
+        } else {
+          Object defaultInstance = tryDefaultInstance(paramTypes[i]);
+          if (defaultInstance == null) {
+            resolvable = false;
+          } else {
+            args[i] = defaultInstance;
+          }
+        }
+      }
+      if (!resolvable) {
+        continue;
+      }
+
+      try {
+        Object instance = ctor.newInstance(args);
+        LOG.debug("Instantiated BlockEncodingManager with fallback constructor {}", ctor);
+        return instance;
+      } catch (ReflectiveOperationException | RuntimeException e) {
+        lastError =
+            new NoSuchMethodException(
+                "Failed invoking BlockEncodingManager constructor " + ctor + ": " + e.getMessage());
+      }
+    }
+
+    throw new NoSuchMethodException(
+        "No usable BlockEncodingManager constructor found in "
+            + blockEncodingManagerClass.getName()
+            + (lastError == null ? "" : " (last error: " + lastError.getMessage() + ")"));
+  }
+
+  private static Object tryDefaultInstance(Class<?> type) {
+    try {
+      Constructor<?> ctor = type.getDeclaredConstructor();
+      if (!ctor.trySetAccessible()) {
+        return null;
+      }
+      return ctor.newInstance();
+    } catch (ReflectiveOperationException | RuntimeException e) {
+      return null;
+    }
+  }
+
+  private static Object defaultPrimitive(Class<?> type) {
+    if (type == boolean.class) return false;
+    if (type == char.class) return '\0';
+    if (type == byte.class) return (byte) 0;
+    if (type == short.class) return (short) 0;
+    if (type == int.class) return 0;
+    if (type == long.class) return 0L;
+    if (type == float.class) return 0f;
+    if (type == double.class) return 0d;
+    throw new IllegalArgumentException("Unsupported primitive type: " + type);
   }
 
   static void registerHandleSerializationModule(ObjectMapper objectMapper) {
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactory.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactory.java
new file mode 100644
index 0000000000..0b0c71c6b6
--- /dev/null
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactory.java
@@ -0,0 +1,74 @@
+/*
+ * 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.trino.connector;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import io.trino.spi.TrinoException;
+import java.util.Map;
+import java.util.Set;
+import org.junit.jupiter.api.Test;
+
+class TestGravitinoConnectorFactory {
+
+  @Test
+  void testSecuritySensitivePropertyNames() {
+    GravitinoConnectorFactory factory = new GravitinoConnectorFactory(null);
+    Map<String, String> config =
+        Map.ofEntries(
+            Map.entry("trino.jdbc.password", "password"),
+            Map.entry("gravitino.client.oauth2.clientSecret", "secret"),
+            Map.entry("hive.s3.aws-access-key", "access-key"),
+            Map.entry("hive.s3.aws-secret-key", "secret-key"),
+            Map.entry("authentication.token", "token"),
+            Map.entry("oauth2.credential", "credential"),
+            Map.entry("tls.private_key", "private-key"),
+            Map.entry("gravitino.uri", "uri"));
+
+    Set<String> sensitivePropertyNames =
+        factory.getSecuritySensitivePropertyNames("catalog", config, null);
+
+    assertThat(sensitivePropertyNames)
+        .containsExactlyInAnyOrder(
+            "trino.jdbc.password",
+            "gravitino.client.oauth2.clientSecret",
+            "hive.s3.aws-access-key",
+            "hive.s3.aws-secret-key",
+            "authentication.token",
+            "oauth2.credential",
+            "tls.private_key");
+    assertThatThrownBy(() -> sensitivePropertyNames.add("another.password"))
+        .isInstanceOf(UnsupportedOperationException.class);
+  }
+
+  @Test
+  void testParseTrinoSpiVersion() {
+    assertThat(GravitinoConnectorFactory.parseTrinoSpiVersion("478")).isEqualTo(478);
+    assertThat(GravitinoConnectorFactory.parseTrinoSpiVersion("478-e")).isEqualTo(478);
+    assertThat(GravitinoConnectorFactory.parseTrinoSpiVersion("478.1-vendor")).isEqualTo(478);
+  }
+
+  @Test
+  void testRejectInvalidTrinoSpiVersion() {
+    assertThatThrownBy(() -> GravitinoConnectorFactory.parseTrinoSpiVersion("starburst-478"))
+        .isInstanceOf(TrinoException.class)
+        .hasMessage("Invalid Trino SPI version 'starburst-478': expected leading digits");
+  }
+}
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/util/json/TestJsonCodec.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/util/json/TestJsonCodec.java
new file mode 100644
index 0000000000..1b76b3000b
--- /dev/null
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/util/json/TestJsonCodec.java
@@ -0,0 +1,105 @@
+/*
+ * 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.trino.connector.util.json;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+import io.trino.FeaturesConfig;
+import java.util.Set;
+import org.junit.jupiter.api.Test;
+
+class TestJsonCodec {
+
+  static class NoArgManager {}
+
+  static class FeaturesConfigManager {
+    final FeaturesConfig featuresConfig;
+
+    public FeaturesConfigManager(FeaturesConfig featuresConfig) {
+      this.featuresConfig = featuresConfig;
+    }
+  }
+
+  static class SetManager {
+    final Set<?> encodings;
+
+    public SetManager(Set<?> encodings) {
+      this.encodings = encodings;
+    }
+  }
+
+  static class FallbackManager {
+    final int flag;
+
+    private FallbackManager(int flag) {
+      this.flag = flag;
+    }
+  }
+
+  static class UnresolvableDependency {
+    UnresolvableDependency(String required) {}
+  }
+
+  static class UnresolvableManager {
+    final UnresolvableDependency dependency;
+
+    private UnresolvableManager(UnresolvableDependency dependency) {
+      this.dependency = dependency;
+    }
+  }
+
+  private static final ClassLoader CLASS_LOADER = TestJsonCodec.class.getClassLoader();
+
+  @Test
+  void testPrefersNoArgConstructor() throws Exception {
+    Object instance = JsonCodec.instantiateBlockEncodingManager(NoArgManager.class, CLASS_LOADER);
+    assertThat(instance).isInstanceOf(NoArgManager.class);
+  }
+
+  @Test
+  void testFallsBackToFeaturesConfigConstructor() throws Exception {
+    Object instance =
+        JsonCodec.instantiateBlockEncodingManager(FeaturesConfigManager.class, CLASS_LOADER);
+    assertThat(instance).isInstanceOfSatisfying(FeaturesConfigManager.class, m -> {});
+  }
+
+  @Test
+  void testFallsBackToSetConstructor() throws Exception {
+    Object instance = JsonCodec.instantiateBlockEncodingManager(SetManager.class, CLASS_LOADER);
+    assertThat(instance)
+        .isInstanceOfSatisfying(SetManager.class, m -> assertThat(m.encodings).isEmpty());
+  }
+
+  @Test
+  void testFallsBackToReflectiveScanForOtherConstructors() throws Exception {
+    Object instance =
+        JsonCodec.instantiateBlockEncodingManager(FallbackManager.class, CLASS_LOADER);
+    assertThat(instance)
+        .isInstanceOfSatisfying(FallbackManager.class, m -> assertThat(m.flag).isEqualTo(0));
+  }
+
+  @Test
+  void testThrowsWhenNoConstructorIsResolvable() {
+    assertThatThrownBy(
+            () ->
+                JsonCodec.instantiateBlockEncodingManager(UnresolvableManager.class, CLASS_LOADER))
+        .isInstanceOf(NoSuchMethodException.class);
+  }
+}


(gravitino) 11/13: [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Address more review findings on the Iceberg REST routing

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diqiu50 pushed a commit to branch trino-irc-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit cef52ce77b2e5c250575f11b22ba4a8bd0833541
Author: diqiu50 <di...@apache.org>
AuthorDate: Mon Aug 24 22:30:39 2026 +0800

    [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Address more review findings on the Iceberg REST routing
    
    - Reload a catalog when its discovered Iceberg REST URI changes, not just
      when Gravitino's lastModifiedTime advances
    - Scope the manual gravitino.iceberg.rest-uri override to a metalake so it
      no longer misroutes other metalakes in multi-metalake mode
    - Fix the deprecated aux-service config WARN firing on every discovery
      poll instead of once per key
    - Redact secrets embedded in the catalog config JSON, not just top-level
      SQL assignments, when logging CREATE CATALOG
    - Let the shared trino-connector module pick its own JDK toolchain by
      trinoVersion so minSupportedTrinoVersion can track the actual minimum
      supported version
    - Dedupe the aux-service prefix constant duplicated across two IT classes
    - Clarify a misleading comment about HashMap put-order priority
    
    (cherry picked from commit 3ec12a854b008c117bf06692b5c61e5e5395f1a2)
---
 build.gradle.kts                                   | 11 +--
 .../client/TestIcebergRestServiceUri.java          | 82 +++++++++++++++++++
 .../auxiliary/AuxiliaryServiceManager.java         | 15 +++-
 docs/trino-connector/configuration.md              |  5 ++
 gradle.properties                                  |  2 +-
 .../gravitino/integration/test/util/BaseIT.java    |  4 +-
 .../web/rest/TestIcebergRESTServiceOperations.java | 10 +++
 .../integration/test/TrinoConnectorIT.java         |  2 -
 .../integration/test/TrinoQueryITBase.java         |  7 +-
 trino-connector/trino-connector/build.gradle.kts   | 30 +++++++
 .../gravitino/trino/connector/GravitinoConfig.java | 25 ++++--
 .../connector/catalog/CatalogConnectorManager.java |  8 +-
 .../trino/connector/catalog/CatalogRegister.java   | 23 ++++++
 .../iceberg/IcebergCatalogPropertyConverter.java   |  6 +-
 .../catalog/iceberg/IcebergConnectorAdapter.java   | 25 +++++-
 .../trino/connector/TestGravitinoConfig.java       | 27 +++++-
 .../connector/catalog/TestCatalogRegister.java     | 18 ++++
 .../iceberg/TestIcebergConnectorAdapterReload.java | 95 ++++++++++++++++++++++
 18 files changed, 360 insertions(+), 35 deletions(-)

diff --git a/build.gradle.kts b/build.gradle.kts
index 08a0128000..ac214df4e9 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -416,16 +416,7 @@ subprojects {
 
   java {
     toolchain {
-      // Some JDK vendors like Homebrew installed OpenJDK 17 have problems in building trino-connector:
-      // It will cause tests of Trino-connector hanging forever on macOS, to avoid this issue and
-      // other vendor-related problems, Gravitino will use the specified AMAZON OpenJDK 17 to build
-      // Trino-connector on macOS.
-      if (project.name == "trino-connector") {
-        if (OperatingSystem.current().isMacOsX) {
-          vendor.set(JvmVendorSpec.AMAZON)
-        }
-        languageVersion.set(JavaLanguageVersion.of(17))
-      } else if (compatibleWithJDK8(project)) {
+      if (compatibleWithJDK8(project)) {
         languageVersion.set(JavaLanguageVersion.of(17))
         sourceCompatibility = JavaVersion.VERSION_1_8
         targetCompatibility = JavaVersion.VERSION_1_8
diff --git a/clients/client-java/src/test/java/org/apache/gravitino/client/TestIcebergRestServiceUri.java b/clients/client-java/src/test/java/org/apache/gravitino/client/TestIcebergRestServiceUri.java
new file mode 100644
index 0000000000..2186118e99
--- /dev/null
+++ b/clients/client-java/src/test/java/org/apache/gravitino/client/TestIcebergRestServiceUri.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied.  See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+package org.apache.gravitino.client;
+
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.google.common.collect.ImmutableMap;
+import java.util.Optional;
+import org.apache.gravitino.dto.responses.ErrorResponse;
+import org.apache.gravitino.dto.responses.IcebergRESTServiceResponse;
+import org.apache.hc.core5.http.HttpStatus;
+import org.apache.hc.core5.http.Method;
+import org.junit.jupiter.api.Assertions;
+import org.junit.jupiter.api.Test;
+
+public class TestIcebergRestServiceUri extends TestBase {
+
+  private static final String ICEBERG_REST_PATH = withSlash("api/system/iceberg-rest");
+
+  @Test
+  public void testIcebergRestServiceUriPresent() throws JsonProcessingException {
+    IcebergRESTServiceResponse resp =
+        new IcebergRESTServiceResponse("http://irc-host:9001/iceberg");
+    buildMockResource(
+        Method.GET,
+        ICEBERG_REST_PATH,
+        ImmutableMap.of("metalake", "test"),
+        null,
+        resp,
+        HttpStatus.SC_OK);
+
+    Optional<String> uri = client.icebergRestServiceUri("test");
+
+    Assertions.assertTrue(uri.isPresent());
+    Assertions.assertEquals("http://irc-host:9001/iceberg", uri.get());
+  }
+
+  @Test
+  public void testIcebergRestServiceUriAbsent() throws JsonProcessingException {
+    IcebergRESTServiceResponse resp = new IcebergRESTServiceResponse(null);
+    buildMockResource(
+        Method.GET,
+        ICEBERG_REST_PATH,
+        ImmutableMap.of("metalake", "test"),
+        null,
+        resp,
+        HttpStatus.SC_OK);
+
+    Optional<String> uri = client.icebergRestServiceUri("test");
+
+    Assertions.assertFalse(uri.isPresent());
+  }
+
+  @Test
+  public void testIcebergRestServiceUriPropagatesServerError() throws JsonProcessingException {
+    ErrorResponse errResp = ErrorResponse.internalError("internal error");
+    buildMockResource(
+        Method.GET,
+        ICEBERG_REST_PATH,
+        ImmutableMap.of("metalake", "test"),
+        null,
+        errResp,
+        HttpStatus.SC_INTERNAL_SERVER_ERROR);
+
+    Assertions.assertThrows(RuntimeException.class, () -> client.icebergRestServiceUri("test"));
+  }
+}
diff --git a/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java b/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java
index 83971c9953..9c67a93583 100644
--- a/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java
+++ b/core/src/main/java/org/apache/gravitino/auxiliary/AuxiliaryServiceManager.java
@@ -32,6 +32,8 @@ import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
 import java.util.ServiceLoader;
+import java.util.Set;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.function.Consumer;
 import java.util.stream.Collectors;
 import org.apache.commons.lang3.StringUtils;
@@ -53,6 +55,9 @@ public class AuxiliaryServiceManager {
 
   private static final Splitter splitter = Splitter.on(",");
   private static final Joiner DOT = Joiner.on(".");
+  // Tracks which deprecated keys have already been warned about, since getAuxServiceConfig
+  // re-extracts the config on every call.
+  private static final Set<String> warnedDeprecatedAuxServiceKeys = ConcurrentHashMap.newKeySet();
 
   private Map<String, GravitinoAuxiliaryService> auxServices = new HashMap<>();
   private Map<String, IsolatedClassLoader> auxServiceClassLoaders = new HashMap<>();
@@ -268,10 +273,12 @@ public class AuxiliaryServiceManager {
         .forEach(
             entry -> {
               String extractKey = entry.getKey().substring(GRAVITINO_AUX_SERVICE_PREFIX.length());
-              LOG.warn(
-                  "The configuration {} is deprecated(still working), please use gravitino.{} instead.",
-                  entry.getKey(),
-                  extractKey);
+              if (warnedDeprecatedAuxServiceKeys.add(entry.getKey())) {
+                LOG.warn(
+                    "The configuration {} is deprecated(still working), please use gravitino.{} instead.",
+                    entry.getKey(),
+                    extractKey);
+              }
               serviceConfigs.put(extractKey, entry.getValue());
             });
     splitter
diff --git a/docs/trino-connector/configuration.md b/docs/trino-connector/configuration.md
index 9e6747ef67..7e6afd07f7 100644
--- a/docs/trino-connector/configuration.md
+++ b/docs/trino-connector/configuration.md
@@ -42,6 +42,11 @@ before. See [Iceberg catalog](./catalog-iceberg.md#how-trino-reaches-the-catalog
 
 Multi-metalake mode (`gravitino.use-single-metalake=false`) is supported on Trino connector versions 440-445 and 469-478. On versions 446-468, a warning is logged and the connector initializes, but the mode is not fully supported and some operations may fail.
 
+**Note:** In multi-metalake mode, `gravitino.iceberg.rest-uri` is only honored when scoped to a
+metalake, as `gravitino.iceberg.rest-uri.<metalake_name>` — the unscoped form is ignored, since a
+single Iceberg REST server serves exactly one metalake and applying it to every metalake would
+misroute the others. The unscoped form remains valid in single-metalake mode.
+
 ## Connecting to a TLS-enabled coordinator
 
 The Gravitino Trino connector registers catalogs by connecting back to the Trino coordinator over
diff --git a/gradle.properties b/gradle.properties
index 4c1ad7e606..05f7d7d451 100644
--- a/gradle.properties
+++ b/gradle.properties
@@ -48,4 +48,4 @@ skipDockerTests = true
 enableFuse = false
 
 # The minimum supported Trino version.
-minSupportedTrinoVersion= 435
+minSupportedTrinoVersion= 440
diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java
index ef45535de9..6a4e41c935 100644
--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java
+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java
@@ -122,6 +122,8 @@ public class BaseIT {
   public static final String DOWNLOAD_SQLITE_JDBC_DRIVER_URL =
       "https://repo1.maven.org/maven2/org/xerial/sqlite-jdbc/3.42.0.0/sqlite-jdbc-3.42.0.0.jar";
 
+  public static final String GRAVITINO_ICEBERG_REST_PREFIX = "gravitino.iceberg-rest.";
+
   public static final Map<String, Pattern> SUPPORTED_CLEAN_CONFLICTS_DRIVER_TYPES =
       ImmutableMap.of(
           "mysql", Pattern.compile("mysql-connector-java-([\\d.]+)\\.jar"),
@@ -688,7 +690,7 @@ public class BaseIT {
 
   protected String getIcebergRestServiceUri() {
     JettyServerConfig jettyServerConfig =
-        JettyServerConfig.fromConfig(serverConfig, String.format("gravitino.iceberg-rest."));
+        JettyServerConfig.fromConfig(serverConfig, GRAVITINO_ICEBERG_REST_PREFIX);
     return String.format(
         "http://%s:%d/iceberg/", jettyServerConfig.getHost(), jettyServerConfig.getHttpPort());
   }
diff --git a/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java b/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java
index f4bb9eddb7..5a559bf059 100644
--- a/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java
+++ b/server/src/test/java/org/apache/gravitino/server/web/rest/TestIcebergRESTServiceOperations.java
@@ -134,6 +134,16 @@ public class TestIcebergRESTServiceOperations {
     assertEquals("http://irc-host:19001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));
   }
 
+  @Test
+  public void testMalformedPortFallsBackToDefaultPort() {
+    IcebergRESTServiceOperations ops =
+        newOps(
+            true,
+            withDynamicProvider(ImmutableMap.of("host", "irc-host", "httpPort", "not-a-number")),
+            "gravitino-host");
+    assertEquals("http://irc-host:9001/iceberg", uriOf(ops.getIcebergRestServiceUri("")));
+  }
+
   @Test
   public void testWildcardHostFallsBackToRequestServerName() {
     IcebergRESTServiceOperations ops =
diff --git a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java
index 968e26fb30..7b04f21da6 100644
--- a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java
+++ b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java
@@ -77,8 +77,6 @@ public class TrinoConnectorIT extends BaseIT {
 
   private static final ContainerSuite containerSuite = ContainerSuite.getInstance();
 
-  private static final String GRAVITINO_ICEBERG_REST_PREFIX = "gravitino.iceberg-rest.";
-
   public static String metalakeName =
       GravitinoITUtils.genRandomName("TrinoIT_metalake").toLowerCase();
   public static String catalogName =
diff --git a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.java b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.java
index e5be0c11c4..405df92076 100644
--- a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.java
+++ b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.java
@@ -47,8 +47,6 @@ import org.slf4j.LoggerFactory;
 public class TrinoQueryITBase {
   private static final Logger LOG = LoggerFactory.getLogger(TrinoQueryITBase.class);
 
-  private static final String GRAVITINO_ICEBERG_REST_PREFIX = "gravitino.iceberg-rest.";
-
   // Auto start docker containers and Gravitino server
   protected static boolean autoStart = true;
 
@@ -95,9 +93,10 @@ public class TrinoQueryITBase {
       // so the auxiliary service has to run and serve this test's metalake.
       baseIT.enableIcebergAuxRestService(
           ImmutableMap.of(
-              GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.ICEBERG_REST_CATALOG_CONFIG_PROVIDER,
+              BaseIT.GRAVITINO_ICEBERG_REST_PREFIX
+                  + IcebergConstants.ICEBERG_REST_CATALOG_CONFIG_PROVIDER,
               IcebergConstants.DYNAMIC_ICEBERG_CATALOG_CONFIG_PROVIDER_NAME,
-              GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_METALAKE,
+              BaseIT.GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_METALAKE,
               metalakeName));
       baseIT.startIntegrationTest();
       gravitinoClient = baseIT.getGravitinoClient();
diff --git a/trino-connector/trino-connector/build.gradle.kts b/trino-connector/trino-connector/build.gradle.kts
index 69ed4e7593..898fc62a4d 100644
--- a/trino-connector/trino-connector/build.gradle.kts
+++ b/trino-connector/trino-connector/build.gradle.kts
@@ -17,6 +17,9 @@
  * under the License.
  */
 
+import net.ltgt.gradle.errorprone.errorprone
+import org.gradle.internal.os.OperatingSystem
+
 plugins {
   id("java")
   id("idea")
@@ -30,6 +33,33 @@ val minSupportedTrinoVersionProperty = providers.gradleProperty("minSupportedTri
 val trinoVersionProperty = providers.gradleProperty("trinoVersion").orElse(minSupportedTrinoVersionProperty)
 val trinoVersion = trinoVersionProperty.map { it.trim().toInt() }.get()
 
+if (trinoVersion >= 440) {
+  // Trino 440+'s trino-spi is compiled for JDK 21+, so this module needs the same JDK 24
+  // toolchain the versioned trino-connector-<range> modules use for the same trinoVersion.
+  // Error Prone is incompatible with that toolchain, so it is disabled here too, matching those
+  // modules' own override.
+  java {
+    toolchain.languageVersion.set(JavaLanguageVersion.of(24))
+  }
+  tasks.withType<JavaCompile>().configureEach {
+    options.errorprone.isEnabled.set(false)
+    options.release.set(17)
+  }
+} else {
+  java {
+    toolchain {
+      // Some JDK vendors like Homebrew installed OpenJDK 17 have problems in building
+      // trino-connector: It will cause tests of Trino-connector hanging forever on macOS, to
+      // avoid this issue and other vendor-related problems, Gravitino will use the specified
+      // AMAZON OpenJDK 17 to build Trino-connector on macOS.
+      if (OperatingSystem.current().isMacOsX) {
+        vendor.set(JvmVendorSpec.AMAZON)
+      }
+      languageVersion.set(JavaLanguageVersion.of(17))
+    }
+  }
+}
+
 dependencies {
   implementation(project(":catalogs:catalog-common"))
   implementation(project(":clients:client-java-runtime", configuration = "shadow"))
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
index b86fa5c5dc..5cdeba701e 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
@@ -742,15 +742,28 @@ public class GravitinoConfig {
   }
 
   /**
-   * Retrieves the manually configured {@code gravitino.iceberg.rest-uri}, if any. Unlike the
-   * discovered endpoint, this is plain local file configuration and is therefore identical and
-   * valid on every node — coordinator and workers alike.
+   * Retrieves the manually configured Iceberg REST server endpoint for the given metalake, if any.
+   * Unlike the discovered endpoint, this is plain local file configuration and is therefore
+   * identical and valid on every node — coordinator and workers alike.
    *
+   * <p>{@code gravitino.iceberg.rest-uri.<metalake>} is checked first. The unscoped {@code
+   * gravitino.iceberg.rest-uri} is honored only in single-metalake mode, where it is unambiguous;
+   * in multi-metalake mode it is ignored, since a single Iceberg REST server serves exactly one
+   * metalake and applying it to every metalake would misroute the others.
+   *
+   * @param metalake the metalake to resolve the override for
    * @return the manually configured Iceberg REST server endpoint, or an empty string when unset
    */
-  public String getManualIcebergRestUri() {
-    return config.getOrDefault(
-        GRAVITINO_ICEBERG_REST_URI.key, GRAVITINO_ICEBERG_REST_URI.defaultValue);
+  public String getManualIcebergRestUri(String metalake) {
+    String scopedValue = config.get(GRAVITINO_ICEBERG_REST_URI.key + "." + metalake);
+    if (StringUtils.isNotBlank(scopedValue)) {
+      return scopedValue;
+    }
+    if (singleMetalakeMode()) {
+      return config.getOrDefault(
+          GRAVITINO_ICEBERG_REST_URI.key, GRAVITINO_ICEBERG_REST_URI.defaultValue);
+    }
+    return GRAVITINO_ICEBERG_REST_URI.defaultValue;
   }
 
   /**
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java
index ce9dc5b7da..b1a809ca7b 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java
@@ -41,6 +41,7 @@ import org.apache.gravitino.client.GravitinoMetalake;
 import org.apache.gravitino.exceptions.NoSuchMetalakeException;
 import org.apache.gravitino.trino.connector.GravitinoConfig;
 import org.apache.gravitino.trino.connector.GravitinoErrorCode;
+import org.apache.gravitino.trino.connector.catalog.iceberg.IcebergConnectorAdapter;
 import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
 import org.apache.gravitino.trino.connector.security.GravitinoAuthProvider;
 import org.slf4j.Logger;
@@ -329,7 +330,12 @@ public class CatalogConnectorManager {
   private void reloadCatalog(GravitinoCatalog catalog) {
     String catalogFullName = getTrinoCatalogName(catalog);
     GravitinoCatalog oldCatalog = catalogConnectors.get(catalogFullName).getCatalog();
-    if (catalog.getLastModifiedTime() <= oldCatalog.getLastModifiedTime()) {
+    // The discovered Iceberg REST endpoint is embedded into the catalog independently of
+    // Gravitino's own lastModifiedTime, so it is checked as a separate reload trigger.
+    boolean icebergRestUriChanged =
+        IcebergConnectorAdapter.hasDiscoveredIcebergRestUriChanged(catalog, oldCatalog, config);
+    if (catalog.getLastModifiedTime() <= oldCatalog.getLastModifiedTime()
+        && !icebergRestUriChanged) {
       return;
     }
 
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
index 4189a251cc..fd971c3bce 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
@@ -72,6 +72,14 @@ public class CatalogRegister {
           "\"([^\"]*(?:credential|token|secret|password)[^\"]*)\"\\s*=\\s*'([^']*)'",
           Pattern.CASE_INSENSITIVE);
 
+  // Matches "key":"value" style secret assignments inside the serialized GravitinoCatalog JSON
+  // that GRAVITINO_DYNAMIC_CONNECTOR_CATALOG_CONFIG carries (e.g. "jdbc-password":"..." or
+  // "s3-secret-key":"..."), which SECRET_PROPERTY_PATTERN's SQL-assignment shape does not match.
+  private static final Pattern SECRET_JSON_PROPERTY_PATTERN =
+      Pattern.compile(
+          "\"([^\"]*(?:credential|token|secret|password)[^\"]*)\"\\s*:\\s*\"([^\"]*)\"",
+          Pattern.CASE_INSENSITIVE);
+
   private Connection connection;
   private boolean isStarted = false;
   private String catalogStoreDirectory;
@@ -342,6 +350,10 @@ public class CatalogRegister {
 
   @VisibleForTesting
   static String redactSecrets(String createCatalogCommand) {
+    return redactJsonSecrets(redactSqlSecrets(createCatalogCommand));
+  }
+
+  private static String redactSqlSecrets(String createCatalogCommand) {
     Matcher matcher = SECRET_PROPERTY_PATTERN.matcher(createCatalogCommand);
     StringBuffer redacted = new StringBuffer();
     while (matcher.find()) {
@@ -352,6 +364,17 @@ public class CatalogRegister {
     return redacted.toString();
   }
 
+  private static String redactJsonSecrets(String createCatalogCommand) {
+    Matcher matcher = SECRET_JSON_PROPERTY_PATTERN.matcher(createCatalogCommand);
+    StringBuffer redacted = new StringBuffer();
+    while (matcher.find()) {
+      matcher.appendReplacement(
+          redacted, Matcher.quoteReplacement("\"" + matcher.group(1) + "\":\"***\""));
+    }
+    matcher.appendTail(redacted);
+    return redacted.toString();
+  }
+
   private String generateDropCatalogCommand(String name) {
     return String.format("DROP CATALOG %s", name);
   }
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
index 14aed17709..ec0237b3b7 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
@@ -131,7 +131,8 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
         throw new UnsupportedOperationException("Unsupported backend type: " + backend);
     }
     Map<String, String> config = new HashMap<>();
-    // The order of put operations determines the priority of parameters.
+    // Later put/putAll calls override earlier ones for the same key; this is call-order
+    // precedence, unrelated to HashMap's (unspecified) iteration order.
     config.putAll(super.gravitinoToEngineProperties(properties));
     config.putAll(stringStringMap);
     config.put("fs.hadoop.enabled", "true");
@@ -169,7 +170,8 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
     }
 
     Map<String, String> config = new HashMap<>();
-    // The order of put operations determines the priority of parameters.
+    // Later put/putAll calls override earlier ones for the same key; this is call-order
+    // precedence, unrelated to HashMap's (unspecified) iteration order.
     config.putAll(buildStorageProperties(catalog.getProperties()));
     config.put(TRINO_ICEBERG_REST_VENDED_CREDENTIALS, "true");
     if (gravitinoConfig.isForwardUser()) {
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java
index 85df20d944..44c06503f8 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java
@@ -88,7 +88,7 @@ public class IcebergConnectorAdapter implements CatalogConnectorAdapter {
     // discovered endpoint is coordinator-only knowledge, so it is read from the catalog's own
     // properties, where the coordinator embeds it at registration time (see
     // embedDiscoveredIcebergRestUri), rather than from GravitinoConfig directly.
-    String restUri = config.getManualIcebergRestUri();
+    String restUri = config.getManualIcebergRestUri(catalog.getMetalake());
     if (StringUtils.isBlank(restUri)) {
       restUri = catalog.getProperty(DISCOVERED_ICEBERG_REST_URI_PROPERTY, "");
     }
@@ -147,6 +147,29 @@ public class IcebergConnectorAdapter implements CatalogConnectorAdapter {
         catalog.getLastModifiedTime());
   }
 
+  /**
+   * Returns whether the Iceberg REST server endpoint currently discovered for {@code catalog}'s
+   * metalake differs from the one embedded into {@code oldCatalog} the last time it was registered.
+   * The catalog's Gravitino {@code lastModifiedTime} does not advance when only Iceberg REST
+   * availability changes, so callers that use it to decide whether to reload a catalog need this as
+   * a separate signal.
+   *
+   * @param catalog the freshly loaded catalog
+   * @param oldCatalog the previously registered version of the same catalog
+   * @param config the connector configuration holding the discovered endpoints
+   * @return {@code true} if {@code catalog} is a lakehouse-iceberg catalog and the discovered
+   *     endpoint for its metalake differs from what {@code oldCatalog} was registered with
+   */
+  public static boolean hasDiscoveredIcebergRestUriChanged(
+      GravitinoCatalog catalog, GravitinoCatalog oldCatalog, GravitinoConfig config) {
+    if (!ICEBERG_PROVIDER.equals(catalog.getProvider())) {
+      return false;
+    }
+    String currentUri = config.getDiscoveredIcebergRestUri(catalog.getMetalake());
+    String previousUri = oldCatalog.getProperty(DISCOVERED_ICEBERG_REST_URI_PROPERTY, "");
+    return !currentUri.equals(previousUri);
+  }
+
   @Override
   public String internalConnectorName() {
     return CONNECTOR_ICEBERG;
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
index 5d03d2e507..d2792d75df 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
@@ -305,7 +305,7 @@ public class TestGravitinoConfig {
     GravitinoConfig config = new GravitinoConfig(ImmutableMap.of("gravitino.metalake", "user_001"));
 
     // Nothing configured, and nothing discovered yet.
-    assertEquals("", config.getManualIcebergRestUri());
+    assertEquals("", config.getManualIcebergRestUri("user_001"));
     assertEquals("", config.getDiscoveredIcebergRestUri("user_001"));
     assertTrue(config.getIcebergRestCatalogConfig().isEmpty());
   }
@@ -324,8 +324,8 @@ public class TestGravitinoConfig {
             "client_id:client_secret");
     GravitinoConfig config = new GravitinoConfig(configMap);
 
-    // A manually configured URI is plain local config, not scoped to any metalake.
-    assertEquals("http://127.0.0.1:9001/iceberg", config.getManualIcebergRestUri());
+    // The unscoped URI is honored as-is in single-metalake mode.
+    assertEquals("http://127.0.0.1:9001/iceberg", config.getManualIcebergRestUri("user_001"));
 
     Map<String, String> restCatalogConfig = config.getIcebergRestCatalogConfig();
     assertEquals(2, restCatalogConfig.size());
@@ -334,6 +334,27 @@ public class TestGravitinoConfig {
         "client_id:client_secret", restCatalogConfig.get("iceberg.rest-catalog.oauth2.credential"));
   }
 
+  @Test
+  public void testIcebergRestConfigScopedToMetalakeInMultiMetalakeMode() {
+    ImmutableMap<String, String> configMap =
+        ImmutableMap.of(
+            "gravitino.metalake",
+            "metalake_a",
+            "gravitino.use-single-metalake",
+            "false",
+            "gravitino.iceberg.rest-uri",
+            "http://unscoped:9001/iceberg",
+            "gravitino.iceberg.rest-uri.metalake_a",
+            "http://metalake-a:9001/iceberg");
+    GravitinoConfig config = new GravitinoConfig(configMap);
+
+    // The scoped key wins for the metalake it names.
+    assertEquals("http://metalake-a:9001/iceberg", config.getManualIcebergRestUri("metalake_a"));
+    // The unscoped key is ignored in multi-metalake mode, since it would otherwise misroute every
+    // metalake other than the one the Iceberg REST server actually serves.
+    assertEquals("", config.getManualIcebergRestUri("metalake_b"));
+  }
+
   @Test
   public void testDiscoveredIcebergRestUriIsPerMetalake() {
     GravitinoConfig config = new GravitinoConfig(ImmutableMap.of("gravitino.metalake", "user_001"));
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java
index 488cfc7ed6..e4248de016 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java
@@ -465,4 +465,22 @@ public class TestCatalogRegister {
     assertTrue(
         redacted.contains("\"gravitino.iceberg.rest-catalog.uri\"='http://irc-host:9001/iceberg'"));
   }
+
+  @Test
+  public void testRedactSecretsMasksJsonEmbeddedSecrets() {
+    String command =
+        "CREATE CATALOG c USING gravitino WITH ( "
+            + "\"__gravitino.dynamic.connector.catalog.config\"="
+            + "'{\"name\":\"hive_catalog\",\"properties\":"
+            + "{\"jdbc-password\":\"hunter2\",\"s3-secret-key\":\"abc123\",\"jdbc-user\":\"admin\"}}')";
+
+    String redacted = CatalogRegister.redactSecrets(command);
+
+    assertFalse(redacted.contains("hunter2"));
+    assertFalse(redacted.contains("abc123"));
+    assertTrue(redacted.contains("\"jdbc-password\":\"***\""));
+    assertTrue(redacted.contains("\"s3-secret-key\":\"***\""));
+    // Non-secret properties must survive redaction unchanged.
+    assertTrue(redacted.contains("\"jdbc-user\":\"admin\""));
+  }
 }
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergConnectorAdapterReload.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergConnectorAdapterReload.java
new file mode 100644
index 0000000000..d90057f24d
--- /dev/null
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergConnectorAdapterReload.java
@@ -0,0 +1,95 @@
+/*
+ * 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.trino.connector.catalog.iceberg;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import com.google.common.collect.ImmutableMap;
+import org.apache.gravitino.trino.connector.GravitinoConfig;
+import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
+import org.junit.jupiter.api.Test;
+
+public class TestIcebergConnectorAdapterReload {
+
+  private static GravitinoConfig configFor(String metalake, String discoveredUri) {
+    GravitinoConfig config =
+        new GravitinoConfig(
+            ImmutableMap.of(
+                "gravitino.uri", "http://127.0.0.1:8090", "gravitino.metalake", metalake));
+    if (discoveredUri != null) {
+      config.setDiscoveredIcebergRestUri(metalake, discoveredUri);
+    }
+    return config;
+  }
+
+  private static GravitinoCatalog icebergCatalog(String embeddedUri) {
+    ImmutableMap<String, String> properties =
+        embeddedUri == null
+            ? ImmutableMap.of()
+            : ImmutableMap.of("__gravitino.iceberg.rest-uri", embeddedUri);
+    return new GravitinoCatalog("test", "lakehouse-iceberg", "iceberg_catalog", properties, 5L);
+  }
+
+  @Test
+  public void testUnchangedWhenDiscoveredUriMatchesEmbeddedUri() {
+    GravitinoConfig config = configFor("test", "http://irc-host:9001/iceberg");
+    GravitinoCatalog freshCatalog = icebergCatalog(null);
+    GravitinoCatalog registeredCatalog = icebergCatalog("http://irc-host:9001/iceberg");
+
+    assertFalse(
+        IcebergConnectorAdapter.hasDiscoveredIcebergRestUriChanged(
+            freshCatalog, registeredCatalog, config));
+  }
+
+  @Test
+  public void testChangedWhenIcebergRestBecomesAvailable() {
+    GravitinoConfig config = configFor("test", "http://irc-host:9001/iceberg");
+    GravitinoCatalog freshCatalog = icebergCatalog(null);
+    GravitinoCatalog registeredCatalog = icebergCatalog(null);
+
+    assertTrue(
+        IcebergConnectorAdapter.hasDiscoveredIcebergRestUriChanged(
+            freshCatalog, registeredCatalog, config));
+  }
+
+  @Test
+  public void testChangedWhenIcebergRestBecomesUnavailable() {
+    GravitinoConfig config = configFor("test", null);
+    GravitinoCatalog freshCatalog = icebergCatalog(null);
+    GravitinoCatalog registeredCatalog = icebergCatalog("http://irc-host:9001/iceberg");
+
+    assertTrue(
+        IcebergConnectorAdapter.hasDiscoveredIcebergRestUriChanged(
+            freshCatalog, registeredCatalog, config));
+  }
+
+  @Test
+  public void testNonIcebergCatalogNeverReportsChanged() {
+    GravitinoConfig config = configFor("test", "http://irc-host:9001/iceberg");
+    GravitinoCatalog freshCatalog =
+        new GravitinoCatalog("test", "hive", "hive_catalog", ImmutableMap.of(), 5L);
+    GravitinoCatalog registeredCatalog =
+        new GravitinoCatalog("test", "hive", "hive_catalog", ImmutableMap.of(), 5L);
+
+    assertFalse(
+        IcebergConnectorAdapter.hasDiscoveredIcebergRestUriChanged(
+            freshCatalog, registeredCatalog, config));
+  }
+}


(gravitino) 05/13: [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Drop Trino 435-439 support

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diqiu50 pushed a commit to branch trino-irc-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit 13969fdcf9177b076260c79d6d8a684efc62689b
Author: diqiu50 <di...@apache.org>
AuthorDate: Sat Aug 22 20:27:06 2026 +0800

    [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Drop Trino 435-439 support
    
    The Iceberg REST routing sets iceberg.rest-catalog.vended-credentials-enabled,
    which Trino only recognizes from 439 onwards. Trino rejects unknown catalog
    properties outright, so 435-438 would fail to load every lakehouse-iceberg
    catalog. Raise the minimum supported version to 440 and remove the
    trino-connector-435-439 module.
    
    (cherry picked from commit c4b3162a8798439ebb11879eb90d835f204e09be)
---
 .github/workflows/trino-multi-version-test.yml     |   6 -
 build.gradle.kts                                   |   1 -
 docs/trino-connector/configuration.md              |   4 +-
 docs/trino-connector/development.md                |   3 -
 docs/trino-connector/installation.md               |   1 -
 docs/trino-connector/requirements.md               |   2 +-
 settings.gradle.kts                                |   1 -
 trino-connector/integration-test/build.gradle.kts  |   1 -
 .../integration/test/TrinoQueryTestTool.java       |   4 +-
 .../trino-test-tools/run_test_with_versions.sh     |   8 +-
 .../trino-cascading-env/docker-compose.yaml        |   4 +-
 .../trino-connector-435-439/build.gradle.kts       | 162 ---------------------
 .../trino/connector/GravitinoConnector435.java     |  55 -------
 .../connector/GravitinoConnectorFactory435.java    |  52 -------
 .../trino/connector/GravitinoMetadata435.java      | 120 ---------------
 .../GravitinoNodePartitioningProvider435.java      |  30 ----
 .../trino/connector/GravitinoPlugin435.java        |  38 -----
 .../trino/connector/GravitinoSplitManager435.java  |  66 ---------
 .../connector/GravitinoSystemConnector435.java     |  87 -----------
 .../META-INF/services/io.trino.spi.Plugin          |  19 ---
 .../src/test/java/TestGravitinoConnector435.java   |  59 --------
 .../gravitino/trino/connector/GravitinoConfig.java |   2 +-
 .../trino/connector/GravitinoConnectorFactory.java |   2 +-
 23 files changed, 13 insertions(+), 714 deletions(-)

diff --git a/.github/workflows/trino-multi-version-test.yml b/.github/workflows/trino-multi-version-test.yml
index a509d4e185..6cf4484f07 100644
--- a/.github/workflows/trino-multi-version-test.yml
+++ b/.github/workflows/trino-multi-version-test.yml
@@ -79,12 +79,6 @@ jobs:
             --auto=all --auto_patch --trino_version=440 \
             --trino_connector_dir=${{ env.CONNECTOR_DIR }}/trino-connector-440-445/build/libs
 
-      - name: Test Trino 435
-        run: |
-          trino-connector/integration-test/trino-test-tools/trino_integration_test.sh \
-            --auto=all --auto_patch --trino_version=435 \
-            --trino_connector_dir=${{ env.CONNECTOR_DIR }}/trino-connector-435-439/build/libs
-
       - name: Upload test reports
         uses: actions/upload-artifact@v7
         if: failure()
diff --git a/build.gradle.kts b/build.gradle.kts
index a62a0ea857..08a0128000 100644
--- a/build.gradle.kts
+++ b/build.gradle.kts
@@ -1004,7 +1004,6 @@ tasks {
   val assembleDistribution by registering(Tar::class) {
     dependsOn(
       compileDistribution,
-      ":trino-connector:trino-connector-435-439:assembleTrinoConnector",
       ":trino-connector:trino-connector-440-445:assembleTrinoConnector",
       ":trino-connector:trino-connector-446-451:assembleTrinoConnector",
       ":trino-connector:trino-connector-452-468:assembleTrinoConnector",
diff --git a/docs/trino-connector/configuration.md b/docs/trino-connector/configuration.md
index 0436de81c5..1d756be8de 100644
--- a/docs/trino-connector/configuration.md
+++ b/docs/trino-connector/configuration.md
@@ -25,7 +25,7 @@ license: "This software is licensed under the Apache License version 2."
 | trino.jdbc.roles                            | string  | (none)                | Session roles applied to the internal JDBC connection, for example `system:sysadmin`. Required by deployments that only allow `CREATE CATALOG` with a privileged role.                                                                                                                                                                           | No       |
 | trino.jdbc.properties.                      | string  | (none)                | The configuration key prefix for raw Trino JDBC driver properties, see [Connecting to a TLS-enabled coordinator](#connecting-to-a-tls-enabled-coordinator).                                                                                                                                                                                      | No       |
 | gravitino.metadata.refresh-interval-seconds | integer | 10                    | The `gravitino.metadata.refresh-interval-seconds` defines the interval in seconds to refresh metadata from Gravitino server, the default value is 10 seconds.                                                                                                                                                                                    | No       |
-| gravitino.trino.skip-version-validation     | boolean | false                 | The `gravitino.trino.skip-version-validation` defines whether to skip Trino version validation. Gravitino supports Trino versions between 435 and 478. If this option is `true`, unsupported Trino versions can still be used, but compatibility is not guaranteed.                                                                              | No       |
+| gravitino.trino.skip-version-validation     | boolean | false                 | The `gravitino.trino.skip-version-validation` defines whether to skip Trino version validation. Gravitino supports Trino versions between 440 and 478. If this option is `true`, unsupported Trino versions can still be used, but compatibility is not guaranteed.                                                                              | No       |
 | gravitino.client.                           | string  | (none)                | The configuration key prefix for the Gravitino client config.                                                                                                                                                                                                                                                                                    | No       |
 | gravitino.trino.skip-catalog-patterns       | string  | (none)                | The `gravitino.trino.skip-catalog-patterns` defines a comma-separated list of catalog name regex patterns that should be excluded from loading. For example, `test_.*, .*_tmp` excludes all catalogs starting with `test_` or ending with `_tmp`.                                                                                                | No       |
 | gravitino.use-single-metalake               | boolean | true                  | If `true`, only one metalake is used and catalogs are identified by `<catalog_name>`. If `false`, multi-metalake mode is enabled and catalogs are identified by `<metalake_name>.<catalog_name>`.                                                                                                                                                | No       |
@@ -45,7 +45,7 @@ or set `gravitino.iceberg.rest-enabled=false` to keep the previous behavior. See
 [Iceberg catalog](./catalog-iceberg.md#how-trino-reaches-the-catalog).
 :::
 
-Multi-metalake mode (`gravitino.use-single-metalake=false`) is supported on Trino connector versions 435-445 and 469-478. On versions 446-468, a warning is logged and the connector initializes, but the mode is not fully supported and some operations may fail.
+Multi-metalake mode (`gravitino.use-single-metalake=false`) is supported on Trino connector versions 440-445 and 469-478. On versions 446-468, a warning is logged and the connector initializes, but the mode is not fully supported and some operations may fail.
 
 ## Connecting to a TLS-enabled coordinator
 
diff --git a/docs/trino-connector/development.md b/docs/trino-connector/development.md
index 5120955a77..a23ce1af19 100644
--- a/docs/trino-connector/development.md
+++ b/docs/trino-connector/development.md
@@ -17,8 +17,6 @@ The Gravitino Trino connector supports multiple Trino versions (see [Requirement
 trino-connector/
 ├── trino-connector/              # Shared base source code
 │   └── src/main/java/            # Common implementation used by all versions
-├── trino-connector-435-439/      # Version-specific adapters for Trino 435-439
-│   └── src/main/java/
 ├── trino-connector-440-445/      # Version-specific adapters for Trino 440-445
 │   └── src/main/java/
 ├── trino-connector-446-451/      # Version-specific adapters for Trino 446-451
@@ -71,7 +69,6 @@ Change `localhost`, `port`, and the names of metalake and catalogs to match your
 
    | Trino Version | Version-Segment Module    |
    |---------------|---------------------------|
-   | 435-439       | `trino-connector-435-439` |
    | 440-445       | `trino-connector-440-445` |
    | 446-451       | `trino-connector-446-451` |
    | 452-468       | `trino-connector-452-468` |
diff --git a/docs/trino-connector/installation.md b/docs/trino-connector/installation.md
index d39b200ee3..8df3373edb 100644
--- a/docs/trino-connector/installation.md
+++ b/docs/trino-connector/installation.md
@@ -19,7 +19,6 @@ Choose the package by your Trino server version first.
 
 | Trino server version | Connector package segment |
 |----------------------|---------------------------|
-| 435-439              | `trino-connector-435-439` |
 | 440-445              | `trino-connector-440-445` |
 | 446-451              | `trino-connector-446-451` |
 | 452-468              | `trino-connector-452-468` |
diff --git a/docs/trino-connector/requirements.md b/docs/trino-connector/requirements.md
index 0c5bb61da4..9224e327d1 100644
--- a/docs/trino-connector/requirements.md
+++ b/docs/trino-connector/requirements.md
@@ -9,7 +9,7 @@ license: "This software is licensed under the Apache License version 2."
 
 To install and deploy the Apache Gravitino Trino connector, the following environmental setup is necessary:
 
-- Trino server version should be between Trino-server-435 and Trino-server-478.
+- Trino server version should be between Trino-server-440 and Trino-server-478.
   The examples in this document use Trino `469` by default.
 - If you use an unsupported Trino version, you can set `gravitino.trino.skip-version-validation` to `true`.
   Unsupported versions have not undergone thorough testing.
diff --git a/settings.gradle.kts b/settings.gradle.kts
index e49a0e4d11..d10537e9a2 100644
--- a/settings.gradle.kts
+++ b/settings.gradle.kts
@@ -75,7 +75,6 @@ val skipTrinoConnector: Boolean =
 if (!skipTrinoConnector) {
   include(
     "trino-connector:trino-connector",
-    "trino-connector:trino-connector-435-439",
     "trino-connector:trino-connector-440-445",
     "trino-connector:trino-connector-446-451",
     "trino-connector:trino-connector-452-468",
diff --git a/trino-connector/integration-test/build.gradle.kts b/trino-connector/integration-test/build.gradle.kts
index c48e9719bf..8264535b6c 100644
--- a/trino-connector/integration-test/build.gradle.kts
+++ b/trino-connector/integration-test/build.gradle.kts
@@ -83,7 +83,6 @@ dependencies {
 }
 
 tasks.register("setupDependencies") {
-  dependsOn(":trino-connector:trino-connector-435-439:copyLibs")
   dependsOn(":trino-connector:trino-connector-440-445:copyLibs")
   dependsOn(":trino-connector:trino-connector-446-451:copyLibs")
   dependsOn(":trino-connector:trino-connector-452-468:copyLibs")
diff --git a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryTestTool.java b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryTestTool.java
index e97843c5df..c0f62d5816 100644
--- a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryTestTool.java
+++ b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryTestTool.java
@@ -99,7 +99,7 @@ public class TrinoQueryTestTool {
               + "otherwise fall back to a single-node setup with combined coordinator-worker roles.");
 
       options.addOption(
-          "trino_version", true, "Specify the Trino version to test, the default value is 435.");
+          "trino_version", true, "Specify the Trino version to test, the default value is 440.");
 
       options.addOption(
           "trino_connector_dir",
@@ -128,7 +128,7 @@ public class TrinoQueryTestTool {
                 + "Run all the testers in the 'testsets' directory with a distributed cluster:\n"
                 + "TrinoTestTool --auto=all --trino_worker_num=3\n\n"
                 + "Run all the testers in the 'testsets' directory with specific trino version:\n"
-                + "TrinoTestTool --auto=all --trino_version=435\n\n"
+                + "TrinoTestTool --auto=all --trino_version=440\n\n"
                 + "Run all the testers in the 'testsets' directory with specific trino connector JAR files:\n"
                 + "TrinoTestTool --auto=all --trino_connector_dir=./trino-connector/libs\n\n"
                 + "Run all the tpch testset's testers in the 'testsets/tpch' directory:\n"
diff --git a/trino-connector/integration-test/trino-test-tools/run_test_with_versions.sh b/trino-connector/integration-test/trino-test-tools/run_test_with_versions.sh
index 2dd6359acb..64c05a2664 100755
--- a/trino-connector/integration-test/trino-test-tools/run_test_with_versions.sh
+++ b/trino-connector/integration-test/trino-test-tools/run_test_with_versions.sh
@@ -23,16 +23,16 @@
 #
 # Arguments:
 # --trino_versions_map: Space-separated list of "version:module" pairs.
-#                       Defaults to "435:trino-connector" if not provided.
+#                       Defaults to "440:trino-connector" if not provided.
 # --trino_test_args:    Arguments passed directly to the underlying test script.
 #
 # Example:
 # ./run_test_with_versions.sh \
-#   --trino_versions_map="435:trino-connector 478:trino-connector-470-478" \
+#   --trino_versions_map="440:trino-connector 478:trino-connector-470-478" \
 #   --trino_test_args="--auto=all"
 #
 # This configuration will run tests for:
-# - Trino 435 using the connector in 'trino-connector' directory
+# - Trino 440 using the connector in 'trino-connector' directory
 # - Trino 478 using the connector in 'trino-connector-470-478' directory
 # And pass "--auto=all" to the underlying test script for each version.
 
@@ -64,7 +64,7 @@ while [[ $# -gt 0 ]]; do
 done
 
 if [ -z "$trino_versions_map" ]; then
-  trino_versions_map="435:trino-connector"
+  trino_versions_map="440:trino-connector"
 fi
 
 for entry in $trino_versions_map; do
diff --git a/trino-connector/integration-test/trino-test-tools/trino-cascading-env/docker-compose.yaml b/trino-connector/integration-test/trino-test-tools/trino-cascading-env/docker-compose.yaml
index 54091d4d62..38e9f40861 100644
--- a/trino-connector/integration-test/trino-test-tools/trino-cascading-env/docker-compose.yaml
+++ b/trino-connector/integration-test/trino-test-tools/trino-cascading-env/docker-compose.yaml
@@ -79,7 +79,7 @@ services:
       start_period: 30s
 
   trino-remote:
-    image: trinodb/trino:435
+    image: trinodb/trino:440
     networks:
       - trino-net
     container_name: trino-ci-trino-remote
@@ -110,7 +110,7 @@ services:
         condition: service_healthy
 
   trino-local:
-    image: trinodb/trino:435
+    image: trinodb/trino:440
     networks:
       - trino-net
     container_name: trino-ci-trino-local
diff --git a/trino-connector/trino-connector-435-439/build.gradle.kts b/trino-connector/trino-connector-435-439/build.gradle.kts
deleted file mode 100644
index befe0343a7..0000000000
--- a/trino-connector/trino-connector-435-439/build.gradle.kts
+++ /dev/null
@@ -1,162 +0,0 @@
-/*
- * 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.
- */
-
-import com.diffplug.gradle.spotless.SpotlessExtension
-import net.ltgt.gradle.errorprone.errorprone
-import org.gradle.internal.hash.ChecksumService
-import org.gradle.kotlin.dsl.support.serviceOf
-
-plugins {
-  `java-library`
-  `maven-publish`
-}
-
-// This module supports Trino versions 435-439
-val minTrinoVersion = 435
-val maxTrinoVersion = 439
-
-val trinoVersion = providers.gradleProperty("trinoVersion")
-  .map { it.trim().toInt() }
-  .orElse(minTrinoVersion)
-  .get()
-
-// Validate version range
-check(trinoVersion in minTrinoVersion..maxTrinoVersion) {
-  "Module ${project.path} supports Trino versions $minTrinoVersion-$maxTrinoVersion, " +
-    "but trinoVersion=$trinoVersion was specified. " +
-    "Please set '-PtrinoVersion=$minTrinoVersion' (or any version in the supported range)."
-}
-
-java {
-  toolchain.languageVersion.set(JavaLanguageVersion.of(24))
-}
-
-dependencies {
-  implementation(project(":catalogs:catalog-common"))
-  implementation(project(":clients:client-java-runtime", configuration = "shadow"))
-  implementation(libs.airlift.json)
-  implementation(libs.bundles.log4j)
-  implementation(libs.commons.collections4)
-  implementation(libs.commons.lang3)
-  implementation("io.trino:trino-jdbc:$trinoVersion")
-  compileOnly(libs.airlift.resolver)
-  compileOnly("io.trino:trino-spi:$trinoVersion") {
-    exclude("org.apache.logging.log4j")
-  }
-  testImplementation(libs.awaitility)
-  testImplementation(libs.mockito.core)
-  testImplementation(libs.mysql.driver)
-  testImplementation("io.trino:trino-memory:$trinoVersion") {
-    exclude("org.antlr")
-    exclude("org.apache.logging.log4j")
-  }
-  testImplementation("io.trino:trino-testing:$trinoVersion") {
-    exclude("org.apache.logging.log4j")
-  }
-  testRuntimeOnly(libs.junit.jupiter.engine)
-}
-
-sourceSets {
-  main {
-    java.srcDirs("../trino-connector/src/main/java")
-  }
-  test {
-    java.srcDirs("../trino-connector/src/test/java")
-    resources.srcDirs("../trino-connector/src/test/resources")
-  }
-}
-
-plugins.withId("com.diffplug.spotless") {
-  configure<SpotlessExtension> {
-    java {
-      // Keep Spotless within this module to avoid cross-project target errors.
-      target(project.fileTree("src") { include("**/*.java") })
-    }
-  }
-}
-
-tasks.withType<JavaCompile>().configureEach {
-  // Error Prone is incompatible with the JDK 24 toolchain required by this Trino range.
-  options.errorprone.isEnabled.set(false)
-  options.release.set(17)
-}
-
-tasks.withType<Test>().configureEach {
-  extensions
-    .findByType(org.gradle.testing.jacoco.plugins.JacocoTaskExtension::class.java)
-    ?.isEnabled = false
-}
-
-tasks {
-  val copyRuntimeLibs by registering(Copy::class) {
-    dependsOn("jar")
-    from({ configurations.runtimeClasspath.get().filter(File::isFile) })
-    into(layout.buildDirectory.dir("libs"))
-  }
-
-  val distributionDir = rootProject.layout.projectDirectory.dir("distribution/${rootProject.name}-${project.name}")
-
-  val copyLibs by registering(Copy::class) {
-    dependsOn(copyRuntimeLibs, "build")
-    from(layout.buildDirectory.dir("libs"))
-    from(rootProject.layout.projectDirectory.dir("licenses")) {
-      into("licenses")
-    }
-    from(rootProject.file("LICENSE.trino"))
-    from(rootProject.file("NOTICE.trino"))
-    from(rootProject.file("README.md"))
-    into(distributionDir)
-    rename { fileName ->
-      fileName.replace(".trino", "")
-    }
-    outputs.dir(distributionDir)
-  }
-
-  val assembleTrinoConnector by registering(Tar::class) {
-    dependsOn(copyLibs)
-    group = "gravitino distribution"
-    finalizedBy("checksumTrinoConnector")
-    val archiveBase = "${rootProject.name}-${project.name}-$version"
-    into(archiveBase)
-    from(distributionDir)
-    compression = Compression.GZIP
-    archiveFileName.set("$archiveBase.tar.gz")
-    destinationDirectory.set(rootProject.layout.projectDirectory.dir("distribution"))
-  }
-
-  val checksumTrinoConnector by registering {
-    group = "gravitino distribution"
-    dependsOn(assembleTrinoConnector)
-    val archiveFile = assembleTrinoConnector.flatMap { it.archiveFile }
-    val checksumFile = archiveFile.map { archive ->
-      archive.asFile.let { it.resolveSibling("${it.name}.sha256") }
-    }
-    inputs.file(archiveFile)
-    outputs.file(checksumFile)
-    doLast {
-      checksumFile.get().writeText(
-        serviceOf<ChecksumService>().sha256(archiveFile.get().asFile).toString()
-      )
-    }
-  }
-
-  named("build") {
-    finalizedBy(copyRuntimeLibs)
-  }
-}
diff --git a/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector435.java b/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector435.java
deleted file mode 100644
index 9d6dc932d4..0000000000
--- a/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnector435.java
+++ /dev/null
@@ -1,55 +0,0 @@
-/*
- * 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.trino.connector;
-
-import io.trino.spi.connector.ConnectorMetadata;
-import io.trino.spi.connector.ConnectorNodePartitioningProvider;
-import io.trino.spi.connector.ConnectorSplitManager;
-import org.apache.gravitino.trino.connector.catalog.CatalogConnectorContext;
-import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadata;
-import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadataAdapter;
-
-public class GravitinoConnector435 extends GravitinoConnector {
-
-  public GravitinoConnector435(CatalogConnectorContext connectorContext) {
-    super(connectorContext);
-  }
-
-  @Override
-  protected GravitinoMetadata createGravitinoMetadata(
-      CatalogConnectorMetadata catalogConnectorMetadata,
-      CatalogConnectorMetadataAdapter metadataAdapter,
-      ConnectorMetadata internalMetadata) {
-    return new GravitinoMetadata435(catalogConnectorMetadata, metadataAdapter, internalMetadata);
-  }
-
-  @Override
-  public ConnectorSplitManager getSplitManager() {
-    ConnectorSplitManager splitManager =
-        catalogConnectorContext.getInternalConnector().getSplitManager();
-    return new GravitinoSplitManager435(splitManager);
-  }
-
-  @Override
-  public ConnectorNodePartitioningProvider getNodePartitioningProvider() {
-    ConnectorNodePartitioningProvider nodePartitioningProvider =
-        catalogConnectorContext.getInternalConnector().getNodePartitioningProvider();
-    return new GravitinoNodePartitioningProvider435(nodePartitioningProvider);
-  }
-}
diff --git a/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory435.java b/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory435.java
deleted file mode 100644
index 2ac78816ce..0000000000
--- a/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory435.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * 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.trino.connector;
-
-import org.apache.gravitino.client.GravitinoAdminClient;
-import org.apache.gravitino.trino.connector.catalog.CatalogConnectorContext;
-import org.apache.gravitino.trino.connector.system.GravitinoSystemConnector;
-import org.apache.gravitino.trino.connector.system.storedprocedure.GravitinoStoredProcedureFactory;
-
-public class GravitinoConnectorFactory435 extends GravitinoConnectorFactory {
-
-  public GravitinoConnectorFactory435(GravitinoAdminClient client) {
-    super(client);
-  }
-
-  @Override
-  protected int getMinSupportTrinoSpiVersion() {
-    return 435;
-  }
-
-  @Override
-  protected int getMaxSupportTrinoSpiVersion() {
-    return 439;
-  }
-
-  @Override
-  protected GravitinoConnector createConnector(CatalogConnectorContext connectorContext) {
-    return new GravitinoConnector435(connectorContext);
-  }
-
-  @Override
-  protected GravitinoSystemConnector createSystemConnector(
-      GravitinoStoredProcedureFactory storedProcedureFactory) {
-    return new GravitinoSystemConnector435(storedProcedureFactory);
-  }
-}
diff --git a/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata435.java b/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata435.java
deleted file mode 100644
index e6b8ff0db6..0000000000
--- a/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoMetadata435.java
+++ /dev/null
@@ -1,120 +0,0 @@
-/*
- * 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.trino.connector;
-
-import io.airlift.slice.Slice;
-import io.trino.spi.connector.ColumnMetadata;
-import io.trino.spi.connector.ConnectorInsertTableHandle;
-import io.trino.spi.connector.ConnectorMergeTableHandle;
-import io.trino.spi.connector.ConnectorOutputMetadata;
-import io.trino.spi.connector.ConnectorOutputTableHandle;
-import io.trino.spi.connector.ConnectorSession;
-import io.trino.spi.connector.ConnectorTableExecuteHandle;
-import io.trino.spi.connector.ConnectorTableHandle;
-import io.trino.spi.connector.RetryMode;
-import io.trino.spi.connector.SchemaTableName;
-import io.trino.spi.statistics.ComputedStatistics;
-import java.util.Collection;
-import java.util.Map;
-import java.util.Optional;
-import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadata;
-import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadataAdapter;
-import org.apache.gravitino.trino.connector.metadata.GravitinoColumn;
-
-public class GravitinoMetadata435 extends GravitinoMetadata {
-
-  public GravitinoMetadata435(
-      CatalogConnectorMetadata catalogConnectorMetadata,
-      CatalogConnectorMetadataAdapter metadataAdapter,
-      io.trino.spi.connector.ConnectorMetadata internalMetadata) {
-    super(catalogConnectorMetadata, metadataAdapter, internalMetadata);
-  }
-
-  @Override
-  public void addColumn(
-      ConnectorSession session, ConnectorTableHandle tableHandle, ColumnMetadata column) {
-    GravitinoColumn gravitinoColumn = metadataAdapter.createColumn(column);
-    catalogConnectorMetadata.addColumn(getTableName(tableHandle), gravitinoColumn);
-  }
-
-  @Override
-  public Optional<ConnectorTableExecuteHandle> getTableHandleForExecute(
-      ConnectorSession session,
-      ConnectorTableHandle tableHandle,
-      String procedureName,
-      Map<String, Object> executeProperties,
-      RetryMode retryMode) {
-    return internalMetadata
-        .getTableHandleForExecute(
-            session,
-            GravitinoHandle.unWrap(tableHandle),
-            procedureName,
-            executeProperties,
-            retryMode)
-        .map(GravitinoTableExecuteHandle::new);
-  }
-
-  @Override
-  public void executeTableExecute(
-      ConnectorSession session, ConnectorTableExecuteHandle tableExecuteHandle) {
-    internalMetadata.executeTableExecute(session, GravitinoHandle.unWrap(tableExecuteHandle));
-  }
-
-  @Override
-  public Optional<ConnectorOutputMetadata> finishInsert(
-      ConnectorSession session,
-      ConnectorInsertTableHandle insertHandle,
-      Collection<Slice> fragments,
-      Collection<ComputedStatistics> computedStatistics) {
-    return internalMetadata.finishInsert(
-        session, GravitinoHandle.unWrap(insertHandle), fragments, computedStatistics);
-  }
-
-  @Override
-  public Optional<ConnectorOutputMetadata> finishCreateTable(
-      ConnectorSession session,
-      ConnectorOutputTableHandle tableHandle,
-      Collection<Slice> fragments,
-      Collection<ComputedStatistics> computedStatistics) {
-    ConnectorInsertTableHandle insertHandle =
-        ((GravitinoOutputTableHandle) tableHandle).getInternalHandle();
-    return internalMetadata.finishInsert(session, insertHandle, fragments, computedStatistics);
-  }
-
-  @Override
-  public ConnectorMergeTableHandle beginMerge(
-      ConnectorSession session, ConnectorTableHandle tableHandle, RetryMode retryMode) {
-    ConnectorMergeTableHandle connectorMergeTableHandle =
-        internalMetadata.beginMerge(session, GravitinoHandle.unWrap(tableHandle), retryMode);
-    SchemaTableName tableName = getTableName(tableHandle);
-
-    return new GravitinoMergeTableHandle(
-        tableName.getSchemaName(), tableName.getTableName(), connectorMergeTableHandle);
-  }
-
-  @Override
-  public void finishMerge(
-      ConnectorSession session,
-      ConnectorMergeTableHandle mergeTableHandle,
-      Collection<Slice> fragments,
-      Collection<ComputedStatistics> computedStatistics) {
-    internalMetadata.finishMerge(
-        session, GravitinoHandle.unWrap(mergeTableHandle), fragments, computedStatistics);
-  }
-}
diff --git a/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoNodePartitioningProvider435.java b/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoNodePartitioningProvider435.java
deleted file mode 100644
index e45753da54..0000000000
--- a/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoNodePartitioningProvider435.java
+++ /dev/null
@@ -1,30 +0,0 @@
-/*
- * 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.trino.connector;
-
-import io.trino.spi.connector.ConnectorNodePartitioningProvider;
-
-/** Trino NodePartitioningProvider implementation with the new split bucket function signature. */
-public class GravitinoNodePartitioningProvider435 extends GravitinoNodePartitioningProvider {
-
-  public GravitinoNodePartitioningProvider435(
-      ConnectorNodePartitioningProvider nodePartitioningProvider) {
-    super(nodePartitioningProvider);
-  }
-}
diff --git a/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoPlugin435.java b/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoPlugin435.java
deleted file mode 100644
index 9a0e8f328a..0000000000
--- a/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoPlugin435.java
+++ /dev/null
@@ -1,38 +0,0 @@
-/*
- * 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.trino.connector;
-
-import org.apache.gravitino.client.GravitinoAdminClient;
-
-/** Trino plugin endpoint, using java spi mechanism */
-public class GravitinoPlugin435 extends GravitinoPlugin {
-
-  public GravitinoPlugin435() {
-    super();
-  }
-
-  public GravitinoPlugin435(GravitinoAdminClient client) {
-    super(client);
-  }
-
-  @Override
-  protected GravitinoConnectorFactory createConnectorFactory(GravitinoAdminClient client) {
-    return new GravitinoConnectorFactory435(client);
-  }
-}
diff --git a/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoSplitManager435.java b/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoSplitManager435.java
deleted file mode 100644
index 306feea732..0000000000
--- a/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoSplitManager435.java
+++ /dev/null
@@ -1,66 +0,0 @@
-/*
- * 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.trino.connector;
-
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import io.trino.spi.connector.ConnectorSplit;
-import io.trino.spi.connector.ConnectorSplitManager;
-import io.trino.spi.connector.ConnectorSplitSource;
-
-public class GravitinoSplitManager435 extends GravitinoSplitManager {
-
-  public GravitinoSplitManager435(ConnectorSplitManager internalSplitManager) {
-    super(internalSplitManager);
-  }
-
-  @Override
-  protected ConnectorSplitSource createSplitSource(ConnectorSplitSource splits) {
-    return new GravitinoSplitSource435(splits);
-  }
-
-  static class GravitinoSplitSource435 extends GravitinoSplitSource {
-
-    GravitinoSplitSource435(ConnectorSplitSource connectorSplitSource) {
-      super(connectorSplitSource);
-    }
-
-    @Override
-    protected ConnectorSplit createSplit(ConnectorSplit split) {
-      return new GravitinoSplit435(split);
-    }
-  }
-
-  public static class GravitinoSplit435 extends GravitinoSplit {
-
-    @JsonCreator
-    public GravitinoSplit435(@JsonProperty(HANDLE_STRING) String handleString) {
-      super(handleString);
-    }
-
-    public GravitinoSplit435(ConnectorSplit split) {
-      super(split);
-    }
-
-    @Override
-    public Object getInfo() {
-      return getInternalHandle().getInfo();
-    }
-  }
-}
diff --git a/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector435.java b/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector435.java
deleted file mode 100644
index e3c3074367..0000000000
--- a/trino-connector/trino-connector-435-439/src/main/java/org/apache/gravitino/trino/connector/GravitinoSystemConnector435.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/*
- * 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.trino.connector;
-
-import com.fasterxml.jackson.annotation.JsonCreator;
-import com.fasterxml.jackson.annotation.JsonProperty;
-import io.trino.spi.Page;
-import io.trino.spi.connector.ConnectorPageSource;
-import io.trino.spi.connector.ConnectorPageSourceProvider;
-import io.trino.spi.connector.ConnectorSplit;
-import io.trino.spi.connector.ConnectorSplitManager;
-import io.trino.spi.connector.SchemaTableName;
-import org.apache.gravitino.trino.connector.system.GravitinoSystemConnector;
-import org.apache.gravitino.trino.connector.system.storedprocedure.GravitinoStoredProcedureFactory;
-
-public class GravitinoSystemConnector435 extends GravitinoSystemConnector {
-
-  public GravitinoSystemConnector435(
-      GravitinoStoredProcedureFactory gravitinoStoredProcedureFactory) {
-    super(gravitinoStoredProcedureFactory);
-  }
-
-  @Override
-  protected ConnectorSplitManager createSplitManager() {
-    return new GravitinoSplitManager435();
-  }
-
-  @Override
-  protected ConnectorPageSourceProvider createPageSourceProvider() {
-    return new DatasourceProvider435();
-  }
-
-  static class DatasourceProvider435 extends DatasourceProvider {
-
-    @Override
-    protected ConnectorPageSource createPageSource(Page page) {
-      return new SystemTablePageSource435(page);
-    }
-  }
-
-  static class GravitinoSplitManager435 extends SplitManager {
-
-    protected ConnectorSplit createSplit(SchemaTableName tableName) {
-      return new Split435(tableName);
-    }
-  }
-
-  static class SystemTablePageSource435 extends SystemTablePageSource {
-
-    public SystemTablePageSource435(Page page) {
-      super(page);
-    }
-
-    public Page getNextPage() {
-      return nextPage();
-    }
-  }
-
-  public static class Split435 extends Split {
-
-    @JsonCreator
-    public Split435(@JsonProperty("tableName") SchemaTableName tableName) {
-      super(tableName);
-    }
-
-    @Override
-    public Object getInfo() {
-      return this;
-    }
-  }
-}
diff --git a/trino-connector/trino-connector-435-439/src/main/resources/META-INF/services/io.trino.spi.Plugin b/trino-connector/trino-connector-435-439/src/main/resources/META-INF/services/io.trino.spi.Plugin
deleted file mode 100644
index aafac3a96c..0000000000
--- a/trino-connector/trino-connector-435-439/src/main/resources/META-INF/services/io.trino.spi.Plugin
+++ /dev/null
@@ -1,19 +0,0 @@
-#
-# 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.
-#
-org.apache.gravitino.trino.connector.GravitinoPlugin435
\ No newline at end of file
diff --git a/trino-connector/trino-connector-435-439/src/test/java/TestGravitinoConnector435.java b/trino-connector/trino-connector-435-439/src/test/java/TestGravitinoConnector435.java
deleted file mode 100644
index eb767c7dda..0000000000
--- a/trino-connector/trino-connector-435-439/src/test/java/TestGravitinoConnector435.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/*
- * 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.
- */
-
-import static io.trino.testing.TestingSession.testSessionBuilder;
-
-import io.trino.Session;
-import io.trino.testing.DistributedQueryRunner;
-import org.apache.gravitino.client.GravitinoAdminClient;
-import org.apache.gravitino.trino.connector.GravitinoPlugin;
-import org.apache.gravitino.trino.connector.GravitinoPlugin435;
-import org.apache.gravitino.trino.connector.TestGravitinoConnector;
-import org.apache.gravitino.trino.connector.TestGravitinoConnectorWithMetalakeCatalogName;
-import org.junit.jupiter.api.Nested;
-
-public class TestGravitinoConnector435 {
-  @Nested
-  class SingleMetalake extends TestGravitinoConnector {
-    @Override
-    protected GravitinoPlugin createGravitinoPlugin(GravitinoAdminClient client) {
-      return new GravitinoPlugin435(client);
-    }
-
-    @Override
-    protected DistributedQueryRunner createTrinoQueryRunner() throws Exception {
-      Session session = testSessionBuilder().setCatalog("gravitino").build();
-      return DistributedQueryRunner.builder(session).setNodeCount(1).build();
-    }
-  }
-
-  @Nested
-  class MultiMetalake extends TestGravitinoConnectorWithMetalakeCatalogName {
-    @Override
-    protected GravitinoPlugin createGravitinoPlugin(GravitinoAdminClient client) {
-      return new GravitinoPlugin435(client);
-    }
-
-    @Override
-    protected DistributedQueryRunner createTrinoQueryRunner() throws Exception {
-      Session session = testSessionBuilder().setCatalog("gravitino").build();
-      return DistributedQueryRunner.builder(session).setNodeCount(1).build();
-    }
-  }
-}
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
index e79645d0e6..b6a518584a 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
@@ -234,7 +234,7 @@ public class GravitinoConfig {
   private static final ConfigEntry GRAVITINO_TRINO_SKIP_VERSION_VALIDATION =
       new ConfigEntry(
           "gravitino.trino.skip-version-validation",
-          "When true, skips Trino version validation and logs a warning instead of throwing an error. Gravitino supports Trino versions 435-439; other versions are untested.",
+          "When true, skips Trino version validation and logs a warning instead of throwing an error. Gravitino supports Trino versions 440-478; other versions are untested.",
           "false",
           false);
 
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java
index 6308b7d1bc..b248ed7f82 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java
@@ -52,7 +52,7 @@ import org.slf4j.LoggerFactory;
 public class GravitinoConnectorFactory implements ConnectorFactory {
 
   private static final Logger LOG = LoggerFactory.getLogger(GravitinoConnectorFactory.class);
-  private static final int MIN_SUPPORT_TRINO_SPI_VERSION = 435;
+  private static final int MIN_SUPPORT_TRINO_SPI_VERSION = 440;
   private static final int MAX_SUPPORT_TRINO_SPI_VERSION = Integer.MAX_VALUE;
   private static final Pattern TRINO_SPI_VERSION_PATTERN = Pattern.compile("^(\\d+)");
   private static final Set<String> SECURITY_SENSITIVE_PROPERTY_SUFFIXES =


(gravitino) 13/13: [Cherry-pick to branch-1.3] fix(trino): share Starburst AI model classes

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diqiu50 pushed a commit to branch trino-irc-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit 3557943b8388fc9726cff77bfad02b3bcb57d149
Author: yuhui <hu...@datastrato.com>
AuthorDate: Mon Aug 24 16:08:13 2026 +0000

    [Cherry-pick to branch-1.3] fix(trino): share Starburst AI model classes
    
    (cherry picked from commit 0d2fd6162049d08a7cb736bbb2a2748684d04816)
---
 .../connector/GravitinoConnectorPluginManager.java | 21 +++++++-------
 .../TestGravitinoConnectorPluginManager.java       | 32 ++++++++++++++++++++++
 2 files changed, 42 insertions(+), 11 deletions(-)

diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorPluginManager.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorPluginManager.java
index ccf59b8e59..9d0d736014 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorPluginManager.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorPluginManager.java
@@ -53,6 +53,15 @@ public class GravitinoConnectorPluginManager {
 
   private static final String PLUGIN_NAME_PREFIX = "gravitino-";
   private static final String PLUGIN_CLASSLOADER_CLASS_NAME = "io.trino.server.PluginClassLoader";
+  static final List<String> PARENT_FIRST_PACKAGES =
+      List.of(
+          "io.trino.spi.",
+          "com.fasterxml.jackson.annotation.",
+          "io.airlift.slice.",
+          "org.openjdk.jol.",
+          "io.opentelemetry.api.",
+          "io.opentelemetry.context.",
+          "io.starburst.ai.model.");
 
   private static volatile GravitinoConnectorPluginManager instance;
 
@@ -175,17 +184,7 @@ public class GravitinoConnectorPluginManager {
       String classLoaderName = PLUGIN_NAME_PREFIX + pluginName;
       // Load Trino SPI package and other dependencies refer to io.trino.server.PluginClassLoader
       Object pluginClassLoader =
-          constructor.newInstance(
-              classLoaderName,
-              urls,
-              appClassloader,
-              List.of(
-                  "io.trino.spi.",
-                  "com.fasterxml.jackson.annotation.",
-                  "io.airlift.slice.",
-                  "org.openjdk.jol.",
-                  "io.opentelemetry.api.",
-                  "io.opentelemetry.context."));
+          constructor.newInstance(classLoaderName, urls, appClassloader, PARENT_FIRST_PACKAGES);
 
       ServiceLoader<Plugin> serviceLoader =
           ServiceLoader.load(Plugin.class, (ClassLoader) pluginClassLoader);
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorPluginManager.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorPluginManager.java
new file mode 100644
index 0000000000..99a6718804
--- /dev/null
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorPluginManager.java
@@ -0,0 +1,32 @@
+/*
+ * 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.trino.connector;
+
+import static org.assertj.core.api.Assertions.assertThat;
+
+import org.junit.jupiter.api.Test;
+
+class TestGravitinoConnectorPluginManager {
+
+  @Test
+  void testStarburstAiModelUsesApplicationClassLoader() {
+    assertThat(GravitinoConnectorPluginManager.PARENT_FIRST_PACKAGES)
+        .contains("io.starburst.ai.model.");
+  }
+}


(gravitino) 03/13: [Cherry-pick to branch-1.3] [#12542] improvement(trino-connector): Support TLS and session role for the internal JDBC connection (#12543)

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diqiu50 pushed a commit to branch trino-irc-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit 378829b44be2038c8830fe5e30ec89a80568a9c9
Author: Yuhui <hu...@datastrato.com>
AuthorDate: Mon Aug 24 20:27:35 2026 +0800

    [Cherry-pick to branch-1.3] [#12542] improvement(trino-connector): Support TLS and session role for the internal JDBC connection (#12543)
---
 docs/trino-connector/configuration.md              | 125 ++++++-
 .../gravitino/trino/connector/GravitinoConfig.java | 242 ++++++++++++-
 .../trino/connector/GravitinoConnectorFactory.java |  49 ++-
 .../connector/catalog/CatalogConnectorManager.java |  17 +-
 .../trino/connector/catalog/CatalogRegister.java   | 214 +++++++++++-
 .../trino/connector/TestGravitinoConfig.java       | 132 +++++++
 .../TestGravitinoConnectorFactoryStart.java        | 152 +++++++++
 .../connector/catalog/TestCatalogRegister.java     | 380 +++++++++++++++++++++
 8 files changed, 1277 insertions(+), 34 deletions(-)

diff --git a/docs/trino-connector/configuration.md b/docs/trino-connector/configuration.md
index 3053ef646d..5bcb98636e 100644
--- a/docs/trino-connector/configuration.md
+++ b/docs/trino-connector/configuration.md
@@ -7,18 +7,28 @@ license: "This software is licensed under the Apache License version 2."
 
 ## Introduction
 
-| Property                                    | Type    | Default Value         | Description                                                                                                                                                                                                                                                                                                         | Required |
-|---------------------------------------------|---------|-----------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|
-| connector.name                              | string  | (none)                | The `connector.name` defines the type of Trino connector, this value is always 'gravitino'.                                                                                                                                                                                                                         | Yes      |
-| gravitino.metalake                          | string  | (none)                | The `gravitino.metalake` defines which metalake in Gravitino server the Trino connector uses. Trino connector should set it at start, the value of `gravitino.metalake` needs to be a valid name, Trino connector can detect and load the metalake with catalogs, schemas and tables once created and keep in sync. | Yes      |
-| gravitino.uri                               | string  | http://localhost:8090 | The `gravitino.uri` defines the connection URL of the Gravitino server, the default value is `http://localhost:8090`. Trino connector can detect and connect to Gravitino server once it is ready, no need to start Gravitino server beforehand.                                                                    | No       |
-| trino.jdbc.user                             | string  | admin                 | The jdbc user name of current Trino.                                                                                                                                                                                                                                                                                | NO       |
-| trino.jdbc.password                         | string  | (none)                | The jdbc password of current Trino.                                                                                                                                                                                                                                                                                 | NO       |
-| gravitino.metadata.refresh-interval-seconds | integer | 10                    | The `gravitino.metadata.refresh-interval-seconds` defines the interval in seconds to refresh metadata from Gravitino server, the default value is 10 seconds.                                                                                                                                                       | No       |
-| gravitino.trino.skip-version-validation     | boolean | false                 | The `gravitino.trino.skip-version-validation` defines whether to skip Trino version validation. Gravitino supports Trino versions between 435 and 478. If this option is `true`, unsupported Trino versions can still be used, but compatibility is not guaranteed.                                                 | No       |
-| gravitino.client.                           | string  | (none)                | The configuration key prefix for the Gravitino client config.                                                                                                                                                                                                                                                       | No       |
-| gravitino.trino.skip-catalog-patterns       | string  | (none)                | The `gravitino.trino.skip-catalog-patterns` defines a comma-separated list of catalog name regex patterns that should be excluded from loading. For example, `test_.*, .*_tmp` excludes all catalogs starting with `test_` or ending with `_tmp`.                                                                   | No       |
-| gravitino.use-single-metalake               | boolean | true                  | If `true`, only one metalake is used and catalogs are identified by `<catalog_name>`. If `false`, multi-metalake mode is enabled and catalogs are identified by `<metalake_name>.<catalog_name>`.                                                                                                                   | No       |
+| Property                                    | Type    | Default Value         | Description                                                                                                                                                                                                                                                                                                                                      | Required |
+|---------------------------------------------|---------|-----------------------|--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|----------|
+| connector.name                              | string  | (none)                | The `connector.name` defines the type of Trino connector, this value is always 'gravitino'.                                                                                                                                                                                                                                                      | Yes      |
+| gravitino.metalake                          | string  | (none)                | The `gravitino.metalake` defines which metalake in Gravitino server the Trino connector uses. Trino connector should set it at start, the value of `gravitino.metalake` needs to be a valid name, Trino connector can detect and load the metalake with catalogs, schemas and tables once created and keep in sync.                              | Yes      |
+| gravitino.uri                               | string  | http://localhost:8090 | The `gravitino.uri` defines the connection URL of the Gravitino server, the default value is `http://localhost:8090`. Trino connector can detect and connect to Gravitino server once it is ready, no need to start Gravitino server beforehand.                                                                                                 | No       |
+| trino.jdbc.user                             | string  | admin                 | The jdbc user name of current Trino.                                                                                                                                                                                                                                                                                                             | NO       |
+| trino.jdbc.password                         | string  | (none)                | The jdbc password of current Trino.                                                                                                                                                                                                                                                                                                              | NO       |
+| trino.jdbc.ssl.enabled                      | boolean | (derived)             | Whether the internal JDBC connection to the Trino coordinator uses TLS. If not set, it is derived from the scheme of the Trino `discovery.uri`, so a coordinator whose `discovery.uri` is `https://...` needs no explicit setting.                                                                                                               | No       |
+| trino.jdbc.ssl.truststore.path              | string  | (none)                | Path of the truststore holding the Trino coordinator certificate. If omitted, the default JVM truststore is used. Requires TLS, which is enabled automatically for an HTTPS `discovery.uri` or explicitly with `trino.jdbc.ssl.enabled=true`, and a `trino.jdbc.ssl.verification` other than `NONE`.                                             | No       |
+| trino.jdbc.ssl.truststore.password          | string  | (none)                | Password of the truststore configured by `trino.jdbc.ssl.truststore.path`. Requires TLS and `trino.jdbc.ssl.truststore.path`, otherwise the connector fails to start.                                                                                                                                                                            | No       |
+| trino.jdbc.ssl.truststore.type              | string  | (none)                | Type of the truststore, for example `JKS` or `PKCS12`. If omitted, the default JVM truststore type is used. Requires TLS and `trino.jdbc.ssl.truststore.path`, otherwise the connector fails to start.                                                                                                                                           | No       |
+| trino.jdbc.ssl.keystore.path                | string  | (none)                | Path of the keystore holding the client certificate presented to the coordinator, for coordinators that require mutual TLS. Requires TLS, which is enabled automatically for an HTTPS `discovery.uri` or explicitly with `trino.jdbc.ssl.enabled=true`, and a `trino.jdbc.ssl.verification` other than `NONE`. See the note on mutual TLS below. | No       |
+| trino.jdbc.ssl.keystore.password            | string  | (none)                | Password of the keystore configured by `trino.jdbc.ssl.keystore.path`. Requires TLS and `trino.jdbc.ssl.keystore.path`, otherwise the connector fails to start.                                                                                                                                                                                  | No       |
+| trino.jdbc.ssl.keystore.type                | string  | (none)                | Type of the keystore, for example `JKS` or `PKCS12`. If omitted, the default JVM keystore type is used. Requires TLS and `trino.jdbc.ssl.keystore.path`, otherwise the connector fails to start.                                                                                                                                                 | No       |
+| trino.jdbc.ssl.verification                 | string  | FULL                  | Certificate verification mode of the internal JDBC connection: `FULL`, `CA` or `NONE`. Any value other than `FULL` requires TLS, which may be derived from an HTTPS `discovery.uri`. `NONE` disables certificate verification entirely and should only be used for troubleshooting.                                                              | No       |
+| trino.jdbc.roles                            | string  | (none)                | Session roles applied to the internal JDBC connection, for example `system:sysadmin`. Required by deployments that only allow `CREATE CATALOG` with a privileged role.                                                                                                                                                                           | No       |
+| trino.jdbc.properties.                      | string  | (none)                | The configuration key prefix for raw Trino JDBC driver properties, see [Connecting to a TLS-enabled coordinator](#connecting-to-a-tls-enabled-coordinator).                                                                                                                                                                                      | No       |
+| gravitino.metadata.refresh-interval-seconds | integer | 10                    | The `gravitino.metadata.refresh-interval-seconds` defines the interval in seconds to refresh metadata from Gravitino server, the default value is 10 seconds.                                                                                                                                                                                    | No       |
+| gravitino.trino.skip-version-validation     | boolean | false                 | The `gravitino.trino.skip-version-validation` defines whether to skip Trino version validation. Gravitino supports Trino versions between 435 and 478. If this option is `true`, unsupported Trino versions can still be used, but compatibility is not guaranteed.                                                                              | No       |
+| gravitino.client.                           | string  | (none)                | The configuration key prefix for the Gravitino client config.                                                                                                                                                                                                                                                                                    | No       |
+| gravitino.trino.skip-catalog-patterns       | string  | (none)                | The `gravitino.trino.skip-catalog-patterns` defines a comma-separated list of catalog name regex patterns that should be excluded from loading. For example, `test_.*, .*_tmp` excludes all catalogs starting with `test_` or ending with `_tmp`.                                                                                                | No       |
+| gravitino.use-single-metalake               | boolean | true                  | If `true`, only one metalake is used and catalogs are identified by `<catalog_name>`. If `false`, multi-metalake mode is enabled and catalogs are identified by `<metalake_name>.<catalog_name>`.                                                                                                                                                | No       |
 
 To configure the Gravitino client, use properties prefixed with `gravitino.client.`. These properties will directly passed to the Gravitino client.
 
@@ -26,6 +36,97 @@ To configure the Gravitino client, use properties prefixed with `gravitino.clien
 
 Multi-metalake mode (`gravitino.use-single-metalake=false`) is supported on Trino connector versions 435-445 and 469-478. On versions 446-468, a warning is logged and the connector initializes, but the mode is not fully supported and some operations may fail.
 
+## Connecting to a TLS-enabled coordinator
+
+The Gravitino Trino connector registers catalogs by connecting back to the Trino coordinator over
+JDBC and running `CREATE CATALOG` / `DROP CATALOG`. This connection is established when the
+connector starts and is reused by the metadata refresh loop, so it must be configured for the
+coordinator's own TLS and authorization settings.
+
+```properties
+connector.name=gravitino
+gravitino.metalake=metalake
+gravitino.uri=http://localhost:8090
+
+# The internal JDBC connection to the coordinator.
+trino.jdbc.user=admin
+trino.jdbc.password=YourSecureTrinoPassword
+trino.jdbc.ssl.truststore.path=/etc/trino/truststore.jks
+trino.jdbc.ssl.truststore.password=YourSecureTruststorePassword
+# Required when the deployment only allows CREATE CATALOG with a privileged role.
+trino.jdbc.roles=system:sysadmin
+```
+
+`trino.jdbc.ssl.enabled` may be omitted when the Trino `discovery.uri` uses the `https` scheme, as
+it is derived from that scheme by default. When `discovery.uri` omits the port, the default port of
+its scheme is used, that is `443` for `https` and `80` for `http`.
+
+The `trino.jdbc.ssl.*` configurations are only meaningful on a TLS-enabled connection. Setting any
+of them while TLS is disabled fails the connector at startup rather than being silently ignored, so
+a misconfigured truststore never degrades into a plaintext connection. Likewise, the truststore
+password and type require a truststore path, and the keystore password and type require a keystore
+path: without one the driver falls back to its default, which they would not apply to.
+
+If the coordinator certificate is signed by a CA the JVM does not trust, import it into a
+truststore and point `trino.jdbc.ssl.truststore.path` at it:
+
+```shell
+# Export the coordinator certificate, then import it into a dedicated truststore.
+openssl s_client -showcerts -connect coordinator.example.com:8443 </dev/null \
+  | openssl x509 -outform PEM > coordinator.pem
+keytool -importcert -noprompt -alias trino-coordinator -file coordinator.pem \
+  -keystore /etc/trino/truststore.jks -storepass YourSecureTruststorePassword
+```
+
+:::caution
+`trino.jdbc.ssl.verification=NONE` disables certificate verification completely and exposes the
+connection to man-in-the-middle attacks. Use it only for troubleshooting; import the coordinator
+certificate into a truststore instead.
+:::
+
+The `trino.jdbc.*` properties are used by the coordinator only. They are never copied into the
+catalogs the connector creates, so the credentials they hold do not reach the generated
+`CREATE CATALOG` statements or the Trino catalog properties files.
+
+### Mutual TLS and certificate authentication
+
+A coordinator that requires mutual TLS also expects a client certificate. Point
+`trino.jdbc.ssl.keystore.path` at the keystore holding it:
+
+```properties
+trino.jdbc.ssl.keystore.path=/etc/trino/client.p12
+trino.jdbc.ssl.keystore.password=YourSecureKeystorePassword
+```
+
+:::note
+The mutual TLS configuration is provided for completeness and has not been verified against a
+coordinator that requires client certificates.
+:::
+
+Trino can also be configured with `http-server.authentication.type=CERTIFICATE`, where the client
+certificate itself is the login and the coordinator derives the username from the certificate
+subject. The connector does not support that authentication type today: it always authenticates
+with `trino.jdbc.user`, so a coordinator configured this way rejects the internal JDBC connection.
+
+### Passing arbitrary JDBC driver properties
+
+Any Trino JDBC driver property that has no dedicated configuration can be passed through with the
+`trino.jdbc.properties.` prefix. The prefix is stripped and the remainder is handed to the driver
+verbatim, overriding the value derived from the dedicated `trino.jdbc.*` configurations:
+
+```properties
+trino.jdbc.properties.KerberosRemoteServiceName=trino
+trino.jdbc.properties.SSLKeyStorePath=/etc/trino/client.p12
+trino.jdbc.properties.SSLKeyStorePassword=YourSecureKeystorePassword
+```
+
+Properties passed through this prefix are handed to the driver without validation, unlike the
+dedicated `trino.jdbc.*` configurations. An unknown name or an invalid value therefore surfaces as a
+driver error when the connection is established, not as a configuration error.
+
+See the [Trino JDBC driver documentation](https://trino.io/docs/current/client/jdbc.html) for the
+full list of supported property names.
+
 ## Authentication
 
 The Gravitino Trino connector supports authenticating to the Gravitino server using Simple, Basic, OAuth, and Kerberos authentication. For detailed authentication configuration, refer to [Trino Connector Authentication](./authentication.md).
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
index 1186fcd1c2..817d9f6306 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
@@ -28,6 +28,7 @@ import java.net.URI;
 import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 import java.util.Properties;
 import java.util.regex.Pattern;
@@ -49,6 +50,8 @@ public class GravitinoConfig {
   public static final String TRINO_CATALOG_STORE = "catalog.store";
   /** The Trino catalog management. */
   public static final String TRINO_CATALOG_MANAGEMENT = "catalog.management";
+  /** The common prefix of all internal Trino JDBC connection configurations. */
+  private static final String TRINO_JDBC_CONFIG_PREFIX = "trino.jdbc.";
 
   // Trino config default value
   /** The Trino catalog config directory default value. */
@@ -57,6 +60,10 @@ public class GravitinoConfig {
   public static final String TRINO_CATALOG_STORE_DEFAULT_VALUE = "file";
   /** The Trino catalog management default value. */
   public static final String TRINO_CATALOG_MANAGEMENT_DEFAULT_VALUE = "static";
+  /** The default port used when the Trino `discovery.uri` omits it and the scheme is http. */
+  private static final int HTTP_DEFAULT_PORT = 80;
+  /** The default port used when the Trino `discovery.uri` omits it and the scheme is https. */
+  private static final int HTTPS_DEFAULT_PORT = 443;
 
   // The Trino configuration of etc/config.properties
   /** The Trino configuration. */
@@ -134,6 +141,86 @@ public class GravitinoConfig {
       new ConfigEntry(
           "trino.jdbc.password", "The JDBC password for connecting to Trino", "", false);
 
+  private static final ConfigEntry TRINO_JDBC_SSL_ENABLED =
+      new ConfigEntry(
+          "trino.jdbc.ssl.enabled",
+          "Whether the internal JDBC connection to the Trino coordinator uses TLS. "
+              + "If not set, it is derived from the scheme of the Trino `discovery.uri`.",
+          "",
+          false);
+
+  private static final ConfigEntry TRINO_JDBC_SSL_TRUSTSTORE_PATH =
+      new ConfigEntry(
+          "trino.jdbc.ssl.truststore.path",
+          "Path of the truststore holding the Trino coordinator certificate. "
+              + "If omitted, the default JVM truststore is used.",
+          "",
+          false);
+
+  private static final ConfigEntry TRINO_JDBC_SSL_TRUSTSTORE_PASSWORD =
+      new ConfigEntry(
+          "trino.jdbc.ssl.truststore.password",
+          "Password of the truststore configured by `trino.jdbc.ssl.truststore.path`",
+          "",
+          false);
+
+  private static final ConfigEntry TRINO_JDBC_SSL_TRUSTSTORE_TYPE =
+      new ConfigEntry(
+          "trino.jdbc.ssl.truststore.type",
+          "Type of the truststore, for example JKS or PKCS12. "
+              + "If omitted, the default JVM truststore type is used.",
+          "",
+          false);
+
+  private static final ConfigEntry TRINO_JDBC_SSL_KEYSTORE_PATH =
+      new ConfigEntry(
+          "trino.jdbc.ssl.keystore.path",
+          "Path of the keystore holding the client certificate presented to the Trino coordinator, "
+              + "used by coordinators that require mutual TLS.",
+          "",
+          false);
+
+  private static final ConfigEntry TRINO_JDBC_SSL_KEYSTORE_PASSWORD =
+      new ConfigEntry(
+          "trino.jdbc.ssl.keystore.password",
+          "Password of the keystore configured by `trino.jdbc.ssl.keystore.path`",
+          "",
+          false);
+
+  private static final ConfigEntry TRINO_JDBC_SSL_KEYSTORE_TYPE =
+      new ConfigEntry(
+          "trino.jdbc.ssl.keystore.type",
+          "Type of the keystore, for example JKS or PKCS12. "
+              + "If omitted, the default JVM keystore type is used.",
+          "",
+          false);
+
+  private static final ConfigEntry TRINO_JDBC_SSL_VERIFICATION =
+      new ConfigEntry(
+          "trino.jdbc.ssl.verification",
+          "Certificate verification mode of the internal JDBC connection: FULL, CA or NONE. "
+              + "NONE disables certificate verification and should only be used for troubleshooting.",
+          "FULL",
+          false);
+
+  private static final ConfigEntry TRINO_JDBC_ROLES =
+      new ConfigEntry(
+          "trino.jdbc.roles",
+          "Session roles applied to the internal JDBC connection, for example `system:sysadmin`. "
+              + "Required by deployments that only allow CREATE CATALOG with a privileged role.",
+          "",
+          false);
+
+  private static final ConfigEntry TRINO_JDBC_EXTRA_PROPERTIES_PREFIX =
+      new ConfigEntry(
+          "trino.jdbc.properties.",
+          "Prefix for Trino JDBC driver properties. Any property beginning with this prefix is "
+              + "passed to the driver verbatim with the prefix removed "
+              + "(e.g., trino.jdbc.properties.KerberosRemoteServiceName=trino), "
+              + "overriding the properties derived from the dedicated `trino.jdbc.*` configurations.",
+          "",
+          false);
+
   private static final ConfigEntry GRAVITINO_METADATA_REFRESH_INTERVAL_SECOND =
       new ConfigEntry(
           "gravitino.metadata.refresh-interval-seconds",
@@ -282,15 +369,25 @@ public class GravitinoConfig {
    * @return the Trino JDBC URI
    */
   public String getTrinoJdbcURI() {
-    String uriString = "";
+    URI trinoURI = parseDiscoveryUri();
+    int port = trinoURI.getPort();
+    if (port < 0) {
+      // `discovery.uri` may omit the port, for example a TLS coordinator behind a load balancer
+      // on the standard HTTPS port. Fall back to the default port of the scheme.
+      port = isHttpsScheme(trinoURI) ? HTTPS_DEFAULT_PORT : HTTP_DEFAULT_PORT;
+    }
+    return String.format("jdbc:trino://%s:%s", trinoURI.getHost(), port);
+  }
+
+  private URI parseDiscoveryUri() {
+    String uriString;
     if (config.containsKey(TRINO_DISCOVERY_URI)) {
       uriString = config.get(TRINO_DISCOVERY_URI);
     } else {
       uriString = trinoConfig.getProperty(TRINO_DISCOVERY_URI);
     }
     try {
-      URI trinoURI = new URI(uriString);
-      return String.format("jdbc:trino://%s:%s", trinoURI.getHost(), trinoURI.getPort());
+      return new URI(uriString);
     } catch (Exception e) {
       throw new TrinoException(
           GravitinoErrorCode.GRAVITINO_MISSING_CONFIG,
@@ -298,6 +395,25 @@ public class GravitinoConfig {
     }
   }
 
+  private static boolean parseBooleanConfig(String key, String value) {
+    // `Boolean.parseBoolean` maps every unrecognized value to false, which would silently disable
+    // TLS for a typo such as `yes`, even when the `discovery.uri` scheme implies it should be on.
+    if ("true".equalsIgnoreCase(value)) {
+      return true;
+    }
+    if ("false".equalsIgnoreCase(value)) {
+      return false;
+    }
+    throw new TrinoException(
+        GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT,
+        String.format(
+            "Invalid value for config '%s': expected true or false, got: %s", key, value));
+  }
+
+  private static boolean isHttpsScheme(URI uri) {
+    return "https".equalsIgnoreCase(uri.getScheme());
+  }
+
   /**
    * Retrieves the region.
    *
@@ -340,6 +456,119 @@ public class GravitinoConfig {
     return config.getOrDefault(TRINO_JDBC_PASSWORD.key, TRINO_JDBC_PASSWORD.defaultValue);
   }
 
+  /**
+   * Returns whether the internal JDBC connection to the Trino coordinator uses TLS.
+   *
+   * <p>If `trino.jdbc.ssl.enabled` is not set, the value is derived from the scheme of the Trino
+   * `discovery.uri`, which is `https` on a TLS enabled coordinator.
+   *
+   * @return true if the internal JDBC connection uses TLS
+   */
+  public boolean isTrinoJdbcSslEnabled() {
+    String value = config.get(TRINO_JDBC_SSL_ENABLED.key);
+    if (StringUtils.isNotBlank(value)) {
+      return parseBooleanConfig(TRINO_JDBC_SSL_ENABLED.key, value.trim());
+    }
+    return isHttpsScheme(parseDiscoveryUri());
+  }
+
+  /**
+   * Retrieves the truststore path of the internal JDBC connection.
+   *
+   * @return the truststore path, or an empty string if not configured
+   */
+  public String getTrinoJdbcSslTruststorePath() {
+    return config.getOrDefault(
+        TRINO_JDBC_SSL_TRUSTSTORE_PATH.key, TRINO_JDBC_SSL_TRUSTSTORE_PATH.defaultValue);
+  }
+
+  /**
+   * Retrieves the truststore password of the internal JDBC connection.
+   *
+   * @return the truststore password, or an empty string if not configured
+   */
+  public String getTrinoJdbcSslTruststorePassword() {
+    return config.getOrDefault(
+        TRINO_JDBC_SSL_TRUSTSTORE_PASSWORD.key, TRINO_JDBC_SSL_TRUSTSTORE_PASSWORD.defaultValue);
+  }
+
+  /**
+   * Retrieves the truststore type of the internal JDBC connection.
+   *
+   * @return the truststore type, or an empty string if not configured
+   */
+  public String getTrinoJdbcSslTruststoreType() {
+    return config.getOrDefault(
+        TRINO_JDBC_SSL_TRUSTSTORE_TYPE.key, TRINO_JDBC_SSL_TRUSTSTORE_TYPE.defaultValue);
+  }
+
+  /**
+   * Retrieves the keystore path of the internal JDBC connection.
+   *
+   * @return the keystore path, or an empty string if not configured
+   */
+  public String getTrinoJdbcSslKeystorePath() {
+    return config.getOrDefault(
+        TRINO_JDBC_SSL_KEYSTORE_PATH.key, TRINO_JDBC_SSL_KEYSTORE_PATH.defaultValue);
+  }
+
+  /**
+   * Retrieves the keystore password of the internal JDBC connection.
+   *
+   * @return the keystore password, or an empty string if not configured
+   */
+  public String getTrinoJdbcSslKeystorePassword() {
+    return config.getOrDefault(
+        TRINO_JDBC_SSL_KEYSTORE_PASSWORD.key, TRINO_JDBC_SSL_KEYSTORE_PASSWORD.defaultValue);
+  }
+
+  /**
+   * Retrieves the keystore type of the internal JDBC connection.
+   *
+   * @return the keystore type, or an empty string if not configured
+   */
+  public String getTrinoJdbcSslKeystoreType() {
+    return config.getOrDefault(
+        TRINO_JDBC_SSL_KEYSTORE_TYPE.key, TRINO_JDBC_SSL_KEYSTORE_TYPE.defaultValue);
+  }
+
+  /**
+   * Retrieves the certificate verification mode of the internal JDBC connection.
+   *
+   * @return the verification mode, one of FULL, CA or NONE
+   */
+  public String getTrinoJdbcSslVerification() {
+    String value = config.get(TRINO_JDBC_SSL_VERIFICATION.key);
+    if (StringUtils.isBlank(value)) {
+      return TRINO_JDBC_SSL_VERIFICATION.defaultValue;
+    }
+    return value.trim().toUpperCase(Locale.ROOT);
+  }
+
+  /**
+   * Retrieves the session roles applied to the internal JDBC connection.
+   *
+   * @return the session roles, or an empty string if not configured
+   */
+  public String getTrinoJdbcRoles() {
+    return config.getOrDefault(TRINO_JDBC_ROLES.key, TRINO_JDBC_ROLES.defaultValue);
+  }
+
+  /**
+   * Retrieves the Trino JDBC driver properties configured with the `trino.jdbc.properties.` prefix.
+   *
+   * @return a map of driver property names, with the prefix removed, to their values
+   */
+  public Map<String, String> getTrinoJdbcExtraProperties() {
+    return config.entrySet().stream()
+        .filter(entry -> entry.getKey().startsWith(TRINO_JDBC_EXTRA_PROPERTIES_PREFIX.key))
+        .filter(entry -> entry.getKey().length() > TRINO_JDBC_EXTRA_PROPERTIES_PREFIX.key.length())
+        .collect(
+            Collectors.toMap(
+                entry -> entry.getKey().substring(TRINO_JDBC_EXTRA_PROPERTIES_PREFIX.key.length()),
+                Map.Entry::getValue));
+  }
+
   /**
    * Retrieves the catalog connector factory class name.
    *
@@ -359,6 +588,13 @@ public class GravitinoConfig {
   public String toCatalogConfig() {
     List<String> stringList = new ArrayList<>();
     for (Map.Entry<String, ConfigEntry> entry : CONFIG_DEFINITIONS.entrySet()) {
+      // The `trino.jdbc.*` configurations are only used by the coordinator to connect back to
+      // Trino. They must not be propagated to the dynamic catalogs, otherwise credentials such as
+      // the JDBC password and the truststore password would end up in the generated CREATE CATALOG
+      // statement, which is logged and persisted into the Trino catalog properties files.
+      if (entry.getKey().startsWith(TRINO_JDBC_CONFIG_PREFIX)) {
+        continue;
+      }
       String value = config.get(entry.getKey());
       if (value != null) {
         stringList.add(String.format("\"%s\"='%s'", entry.getKey(), value));
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java
index 5315342713..6308b7d1bc 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConnectorFactory.java
@@ -64,6 +64,7 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
   private GravitinoSystemTableFactory gravitinoSystemTableFactory;
 
   private CatalogConnectorManager catalogConnectorManager;
+  private boolean catalogConnectorManagerStartTriggered = false;
 
   private GravitinoAdminClient client;
   private int trinoVersion;
@@ -87,6 +88,16 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
     return catalogConnectorManager;
   }
 
+  /**
+   * Returns whether starting the catalog connector manager has been triggered.
+   *
+   * @return true if starting the catalog connector manager has been triggered
+   */
+  @VisibleForTesting
+  public boolean isCatalogConnectorManagerStartTriggered() {
+    return catalogConnectorManagerStartTriggered;
+  }
+
   /**
    * This function call by Trino creates a connector. It creates GravitinoSystemConnector at first.
    * Another time's it get GravitinoConnector by CatalogConnectorManager
@@ -104,9 +115,14 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
     GravitinoConfig config = new GravitinoConfig(requiredConfig);
 
     synchronized (this) {
+      // Keep the version check out of the try below so that it keeps reporting its own error code
+      // instead of being wrapped as a generic initialization failure.
       if (catalogConnectorManager == null) {
         checkTrinoSpiVersion(trinoConnectorContext, config);
-        try {
+      }
+
+      try {
+        if (catalogConnectorManager == null) {
           CatalogRegister catalogRegister = new CatalogRegister();
 
           CatalogConnectorFactory catalogConnectorFactory = createCatalogConnectorFactory(config);
@@ -115,16 +131,31 @@ public class GravitinoConnectorFactory implements ConnectorFactory {
                   catalogRegister, catalogConnectorFactory, this::getTrinoCatalogName);
           catalogConnectorManager.config(config, client);
 
-          if (isCoordinator(trinoConnectorContext)) {
-            catalogConnectorManager.start();
-          }
-
           gravitinoSystemTableFactory = new GravitinoSystemTableFactory(catalogConnectorManager);
-        } catch (Exception e) {
-          String message = "Initialization of the GravitinoConnector failed " + e.getMessage();
-          LOG.error(message);
-          throw new TrinoException(GRAVITINO_RUNTIME_ERROR, message, e);
         }
+
+        // The `trino.jdbc.*` settings that CatalogRegister needs to connect back to the
+        // coordinator are deliberately not propagated to the dynamic catalogs, so they are only
+        // present in the configuration of the static connector. Trino does not guarantee that the
+        // static catalog is loaded before the catalogs Gravitino created, therefore the manager is
+        // started from the static connector only, re-applying its configuration in case a dynamic
+        // connector was created first.
+        if (!catalogConnectorManagerStartTriggered
+            && !config.isDynamicConnector()
+            && isCoordinator(trinoConnectorContext)) {
+          // Triggered before start() on purpose: everything that makes it fail is a
+          // configuration error, and retrying on the next create() would only open another
+          // connection.
+          catalogConnectorManagerStartTriggered = true;
+          // Only the configuration is re-applied here: rebuilding the Gravitino client would leak
+          // the one a dynamic connector may have already built.
+          catalogConnectorManager.updateConfig(config);
+          catalogConnectorManager.start();
+        }
+      } catch (Exception e) {
+        String message = "Initialization of the GravitinoConnector failed " + e.getMessage();
+        LOG.error(message);
+        throw new TrinoException(GRAVITINO_RUNTIME_ERROR, message, e);
       }
     }
 
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java
index 7539a0b439..34872d2e2f 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogConnectorManager.java
@@ -114,8 +114,7 @@ public class CatalogConnectorManager {
    * @param client the Gravitino admin client
    */
   public void config(GravitinoConfig config, GravitinoAdminClient client) {
-    Preconditions.checkArgument(config != null, "config must not be null");
-    this.config = config;
+    updateConfig(config);
     if (client == null) {
       String authType =
           config.getClientConfig().getOrDefault(GravitinoAuthProvider.AUTH_TYPE_KEY, "none");
@@ -142,6 +141,20 @@ public class CatalogConnectorManager {
     } else {
       this.gravitinoClient = client;
     }
+  }
+
+  /**
+   * Updates the Gravitino configuration, leaving the Gravitino client untouched.
+   *
+   * <p>Used to re-apply the configuration of the static connector when a dynamic connector created
+   * the manager first, so that the catalog register is started with the `trino.jdbc.*` settings
+   * that are only present in the static configuration.
+   *
+   * @param config the Gravitino configuration
+   */
+  public void updateConfig(GravitinoConfig config) {
+    Preconditions.checkArgument(config != null, "config must not be null");
+    this.config = config;
     this.metadataUpdateIntervalSecond = Integer.parseInt(config.getMetadataRefreshIntervalSecond());
     this.targetMetalake = config.getMetalake();
   }
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
index 09bf1cd658..faca9c2499 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/CatalogRegister.java
@@ -21,17 +21,21 @@ package org.apache.gravitino.trino.connector.catalog;
 import static org.apache.gravitino.trino.connector.GravitinoConfig.GRAVITINO_DYNAMIC_CONNECTOR;
 import static org.apache.gravitino.trino.connector.GravitinoConfig.GRAVITINO_DYNAMIC_CONNECTOR_CATALOG_CONFIG;
 
+import com.google.common.annotations.VisibleForTesting;
+import com.google.common.collect.ImmutableSet;
 import io.trino.jdbc.TrinoDriver;
 import io.trino.spi.TrinoException;
 import java.io.File;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.sql.Connection;
-import java.sql.DriverManager;
 import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
+import java.util.Map;
 import java.util.Properties;
+import java.util.Set;
+import org.apache.commons.lang3.StringUtils;
 import org.apache.gravitino.trino.connector.GravitinoConfig;
 import org.apache.gravitino.trino.connector.GravitinoErrorCode;
 import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
@@ -49,6 +53,12 @@ public class CatalogRegister {
   private static final int EXECUTE_QUERY_MAX_RETRIES = 6;
   private static final int EXECUTE_QUERY_BACKOFF_TIME_SECOND = 5;
 
+  private static final String SSL_VERIFICATION_FULL = "FULL";
+  private static final String SSL_VERIFICATION_CA = "CA";
+  private static final String SSL_VERIFICATION_NONE = "NONE";
+  private static final Set<String> SSL_VERIFICATION_MODES =
+      ImmutableSet.of(SSL_VERIFICATION_FULL, SSL_VERIFICATION_CA, SSL_VERIFICATION_NONE);
+
   private Connection connection;
   private boolean isStarted = false;
   private String catalogStoreDirectory;
@@ -80,17 +90,16 @@ public class CatalogRegister {
     this.config = config;
 
     TrinoDriver driver = new TrinoDriver();
-    DriverManager.registerDriver(driver);
-
-    Properties properties = new Properties();
-    properties.put("user", config.getTrinoUser());
-    properties.put("password", config.getTrinoPassword());
+    Properties properties = buildJdbcProperties(config);
+    String jdbcUri = config.getTrinoJdbcURI();
     try {
-      connection = driver.connect(config.getTrinoJdbcURI(), properties);
+      connection = driver.connect(jdbcUri, properties);
     } catch (SQLException e) {
       throw new TrinoException(
           GravitinoErrorCode.GRAVITINO_RUNTIME_ERROR,
-          "Failed to initialize the Trino connection.",
+          String.format(
+              "Failed to initialize the Trino connection to %s (TLS %s).",
+              jdbcUri, config.isTrinoJdbcSslEnabled() ? "enabled" : "disabled"),
           e);
     }
 
@@ -104,6 +113,195 @@ public class CatalogRegister {
     }
   }
 
+  /**
+   * Builds the JDBC properties used by the internal connection to the Trino coordinator.
+   *
+   * <p>The properties derived from the dedicated {@code trino.jdbc.*} configurations are applied
+   * first, then the raw driver properties configured with the {@code trino.jdbc.properties.} prefix
+   * are applied on top of them, so that any driver property can be overridden.
+   *
+   * @param config the Gravitino configuration
+   * @return the JDBC properties
+   */
+  @VisibleForTesting
+  static Properties buildJdbcProperties(GravitinoConfig config) {
+    boolean sslEnabled = config.isTrinoJdbcSslEnabled();
+    String verification = config.getTrinoJdbcSslVerification();
+    String truststorePath = config.getTrinoJdbcSslTruststorePath();
+    String truststorePassword = config.getTrinoJdbcSslTruststorePassword();
+    String truststoreType = config.getTrinoJdbcSslTruststoreType();
+    String keystorePath = config.getTrinoJdbcSslKeystorePath();
+    String keystorePassword = config.getTrinoJdbcSslKeystorePassword();
+    String keystoreType = config.getTrinoJdbcSslKeystoreType();
+    String roles = config.getTrinoJdbcRoles();
+
+    validateSslConfig(
+        sslEnabled,
+        verification,
+        truststorePath,
+        truststorePassword,
+        truststoreType,
+        keystorePath,
+        keystorePassword,
+        keystoreType);
+
+    Properties properties = new Properties();
+    properties.put("user", config.getTrinoUser());
+    String password = config.getTrinoPassword();
+    if (StringUtils.isNotEmpty(password)) {
+      properties.put("password", password);
+    }
+
+    if (sslEnabled) {
+      properties.put("SSL", "true");
+      properties.put("SSLVerification", verification);
+      if (StringUtils.isNotBlank(truststorePath)) {
+        properties.put("SSLTrustStorePath", truststorePath);
+      }
+      if (StringUtils.isNotEmpty(truststorePassword)) {
+        properties.put("SSLTrustStorePassword", truststorePassword);
+      }
+      if (StringUtils.isNotBlank(truststoreType)) {
+        properties.put("SSLTrustStoreType", truststoreType);
+      }
+      if (StringUtils.isNotBlank(keystorePath)) {
+        properties.put("SSLKeyStorePath", keystorePath);
+      }
+      if (StringUtils.isNotEmpty(keystorePassword)) {
+        properties.put("SSLKeyStorePassword", keystorePassword);
+      }
+      if (StringUtils.isNotBlank(keystoreType)) {
+        properties.put("SSLKeyStoreType", keystoreType);
+      }
+    }
+
+    if (StringUtils.isNotBlank(roles)) {
+      properties.put("roles", roles);
+    }
+
+    Map<String, String> extraProperties = config.getTrinoJdbcExtraProperties();
+    if (!extraProperties.isEmpty()) {
+      // Log the names only, the values may contain credentials.
+      LOG.debug("Applying extra Trino JDBC properties: {}", extraProperties.keySet());
+      extraProperties.keySet().stream()
+          .filter(key -> key.startsWith("SSL") && properties.containsKey(key))
+          .forEach(
+              key ->
+                  LOG.warn(
+                      "Extra Trino JDBC property '{}' overrides the TLS setting derived from the "
+                          + "dedicated configuration and is applied without validation",
+                      key));
+      properties.putAll(extraProperties);
+    }
+    return properties;
+  }
+
+  private static void validateSslConfig(
+      boolean sslEnabled,
+      String verification,
+      String truststorePath,
+      String truststorePassword,
+      String truststoreType,
+      String keystorePath,
+      String keystorePassword,
+      String keystoreType) {
+    if (!SSL_VERIFICATION_MODES.contains(verification)) {
+      throw new TrinoException(
+          GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT,
+          String.format(
+              "Invalid value for config 'trino.jdbc.ssl.verification': expected one of %s, got: %s",
+              SSL_VERIFICATION_MODES, verification));
+    }
+
+    if (!sslEnabled) {
+      if (!SSL_VERIFICATION_FULL.equals(verification)) {
+        throw new TrinoException(
+            GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT,
+            "Config 'trino.jdbc.ssl.verification' requires TLS to be enabled either by an HTTPS "
+                + "'discovery.uri' or by 'trino.jdbc.ssl.enabled=true'");
+      }
+      checkRequiresSslEnabled("trino.jdbc.ssl.truststore.path", truststorePath);
+      checkRequiresSslEnabled("trino.jdbc.ssl.truststore.password", truststorePassword);
+      checkRequiresSslEnabled("trino.jdbc.ssl.truststore.type", truststoreType);
+      checkRequiresSslEnabled("trino.jdbc.ssl.keystore.path", keystorePath);
+      checkRequiresSslEnabled("trino.jdbc.ssl.keystore.password", keystorePassword);
+      checkRequiresSslEnabled("trino.jdbc.ssl.keystore.type", keystoreType);
+      return;
+    }
+
+    validateKeystoreConfig(verification, keystorePath, keystorePassword, keystoreType);
+
+    if (StringUtils.isBlank(truststorePath)) {
+      // The driver falls back to the default JVM truststore, which the password and the type of a
+      // truststore that was never configured have nothing to apply to.
+      checkRequires(
+          "trino.jdbc.ssl.truststore.password",
+          truststorePassword,
+          "trino.jdbc.ssl.truststore.path");
+      checkRequires(
+          "trino.jdbc.ssl.truststore.type", truststoreType, "trino.jdbc.ssl.truststore.path");
+      return;
+    }
+
+    if (SSL_VERIFICATION_NONE.equals(verification)) {
+      throw new TrinoException(
+          GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT,
+          "Config 'trino.jdbc.ssl.truststore.path' cannot be used with "
+              + "'trino.jdbc.ssl.verification' = NONE");
+    }
+    if (!Files.exists(Path.of(truststorePath))) {
+      throw new TrinoException(
+          GravitinoErrorCode.GRAVITINO_MISSING_CONFIG,
+          String.format(
+              "The truststore file configured by 'trino.jdbc.ssl.truststore.path' does not exist: %s",
+              truststorePath));
+    }
+  }
+
+  private static void validateKeystoreConfig(
+      String verification, String keystorePath, String keystorePassword, String keystoreType) {
+    if (StringUtils.isBlank(keystorePath)) {
+      checkRequires(
+          "trino.jdbc.ssl.keystore.password", keystorePassword, "trino.jdbc.ssl.keystore.path");
+      checkRequires("trino.jdbc.ssl.keystore.type", keystoreType, "trino.jdbc.ssl.keystore.path");
+      return;
+    }
+    if (SSL_VERIFICATION_NONE.equals(verification)) {
+      // The driver rejects the keystore properties in this combination, so fail with a config
+      // error here rather than letting it surface as a connection failure.
+      throw new TrinoException(
+          GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT,
+          "Config 'trino.jdbc.ssl.keystore.path' cannot be used with "
+              + "'trino.jdbc.ssl.verification' = NONE");
+    }
+    if (!Files.exists(Path.of(keystorePath))) {
+      throw new TrinoException(
+          GravitinoErrorCode.GRAVITINO_MISSING_CONFIG,
+          String.format(
+              "The keystore file configured by 'trino.jdbc.ssl.keystore.path' does not exist: %s",
+              keystorePath));
+    }
+  }
+
+  private static void checkRequires(String key, String value, String requiredKey) {
+    if (StringUtils.isNotEmpty(value)) {
+      throw new TrinoException(
+          GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT,
+          String.format("Config '%s' requires '%s' to be set", key, requiredKey));
+    }
+  }
+
+  private static void checkRequiresSslEnabled(String key, String value) {
+    if (StringUtils.isNotEmpty(value)) {
+      throw new TrinoException(
+          GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT,
+          String.format(
+              "Config '%s' requires TLS to be enabled either by an HTTPS 'discovery.uri' or by "
+                  + "'trino.jdbc.ssl.enabled=true'",
+              key));
+    }
+  }
+
   private String generateCreateCatalogCommand(String name, GravitinoCatalog gravitinoCatalog)
       throws Exception {
     return String.format(
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
index 8aa65b4b69..2d486b52c0 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
@@ -21,6 +21,7 @@ package org.apache.gravitino.trino.connector;
 import static org.apache.gravitino.trino.connector.GravitinoErrorCode.GRAVITINO_MISSING_CONFIG;
 import static org.junit.jupiter.api.Assertions.assertEquals;
 import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertThrowsExactly;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
@@ -168,6 +169,137 @@ public class TestGravitinoConfig {
     assertTrue(catalogConfig.contains("\"gravitino.user\"='admin'"));
   }
 
+  @Test
+  public void testTrinoJdbcConfigDefaults() {
+    GravitinoConfig config =
+        new GravitinoConfig(
+            ImmutableMap.of("gravitino.metalake", "user_001", "discovery.uri", "http://host:8080"));
+
+    assertEquals("admin", config.getTrinoUser());
+    assertEquals("", config.getTrinoPassword());
+    assertFalse(config.isTrinoJdbcSslEnabled());
+    assertEquals("FULL", config.getTrinoJdbcSslVerification());
+    assertEquals("", config.getTrinoJdbcSslTruststorePath());
+    assertEquals("", config.getTrinoJdbcSslTruststorePassword());
+    assertEquals("", config.getTrinoJdbcSslTruststoreType());
+    assertEquals("", config.getTrinoJdbcRoles());
+    assertTrue(config.getTrinoJdbcExtraProperties().isEmpty());
+  }
+
+  @Test
+  public void testTrinoJdbcSslEnabledDerivedFromDiscoveryUri() {
+    GravitinoConfig config =
+        new GravitinoConfig(
+            ImmutableMap.of(
+                "gravitino.metalake", "user_001", "discovery.uri", "https://host:8443"));
+
+    assertTrue(config.isTrinoJdbcSslEnabled());
+    assertEquals("jdbc:trino://host:8443", config.getTrinoJdbcURI());
+  }
+
+  @Test
+  public void testTrinoJdbcExtraProperties() {
+    GravitinoConfig config =
+        new GravitinoConfig(
+            ImmutableMap.of(
+                "gravitino.metalake",
+                "user_001",
+                "discovery.uri",
+                "http://host:8080",
+                "trino.jdbc.properties.KerberosRemoteServiceName",
+                "trino",
+                "trino.jdbc.properties.SSLKeyStorePath",
+                "/etc/trino/client.p12"));
+
+    Map<String, String> extraProperties = config.getTrinoJdbcExtraProperties();
+    assertEquals(2, extraProperties.size());
+    assertEquals("trino", extraProperties.get("KerberosRemoteServiceName"));
+    assertEquals("/etc/trino/client.p12", extraProperties.get("SSLKeyStorePath"));
+  }
+
+  @Test
+  public void testToCatalogConfigExcludesTrinoJdbcProperties() {
+    GravitinoConfig config =
+        new GravitinoConfig(
+            ImmutableMap.of(
+                "gravitino.metalake",
+                "user_001",
+                "trino.jdbc.user",
+                "admin",
+                "trino.jdbc.password",
+                "jdbc-secret",
+                "trino.jdbc.ssl.truststore.password",
+                "truststore-secret",
+                "trino.jdbc.properties.SSLKeyStorePassword",
+                "keystore-secret"));
+
+    // The internal JDBC connection settings are coordinator only. They must never reach the
+    // generated CREATE CATALOG statement, which is logged and persisted to the catalog files.
+    String catalogConfig = config.toCatalogConfig();
+    assertFalse(catalogConfig.contains("trino.jdbc."));
+    assertFalse(catalogConfig.contains("secret"));
+    assertTrue(catalogConfig.contains("\"gravitino.metalake\"='user_001'"));
+  }
+
+  @Test
+  public void testTrinoJdbcUriUsesSchemeDefaultPort() {
+    GravitinoConfig httpsConfig =
+        new GravitinoConfig(
+            ImmutableMap.of("gravitino.metalake", "user_001", "discovery.uri", "https://host"));
+    assertEquals("jdbc:trino://host:443", httpsConfig.getTrinoJdbcURI());
+
+    GravitinoConfig httpConfig =
+        new GravitinoConfig(
+            ImmutableMap.of("gravitino.metalake", "user_001", "discovery.uri", "http://host"));
+    assertEquals("jdbc:trino://host:80", httpConfig.getTrinoJdbcURI());
+  }
+
+  @Test
+  public void testBlankSslVerificationFallsBackToDefault() {
+    GravitinoConfig config =
+        new GravitinoConfig(
+            ImmutableMap.of(
+                "gravitino.metalake",
+                "user_001",
+                "discovery.uri",
+                "http://host:8080",
+                "trino.jdbc.ssl.verification",
+                "  "));
+
+    assertEquals("FULL", config.getTrinoJdbcSslVerification());
+  }
+
+  @Test
+  public void testInvalidSslEnabledIsRejected() {
+    GravitinoConfig config =
+        new GravitinoConfig(
+            ImmutableMap.of(
+                "gravitino.metalake",
+                "user_001",
+                // An HTTPS discovery.uri would have derived true, so a typo must not silently
+                // fall back to false.
+                "discovery.uri",
+                "https://host:8443",
+                "trino.jdbc.ssl.enabled",
+                "yes"));
+
+    TrinoException e = assertThrows(TrinoException.class, config::isTrinoJdbcSslEnabled);
+    assertTrue(e.getMessage().contains("trino.jdbc.ssl.enabled"));
+    assertTrue(e.getMessage().contains("expected true or false"));
+  }
+
+  @Test
+  public void testSslEnabledAcceptsMixedCase() {
+    GravitinoConfig config =
+        new GravitinoConfig(
+            ImmutableMap.of(
+                "gravitino.metalake", "user_001",
+                "discovery.uri", "http://host:8080",
+                "trino.jdbc.ssl.enabled", " TRUE "));
+
+    assertTrue(config.isTrinoJdbcSslEnabled());
+  }
+
   private static boolean skipCatalog(String catalogName, GravitinoConfig config) {
     for (Pattern pattern : config.getSkipCatalogPatterns()) {
       if (pattern.matcher(catalogName).matches()) {
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactoryStart.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactoryStart.java
new file mode 100644
index 0000000000..b104b4d509
--- /dev/null
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConnectorFactoryStart.java
@@ -0,0 +1,152 @@
+/*
+ * 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.trino.connector;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import com.google.common.collect.ImmutableMap;
+import io.trino.spi.connector.ConnectorContext;
+import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.Map;
+import org.apache.gravitino.client.GravitinoAdminClient;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+/**
+ * Verifies that the catalog connector manager is only started from the static connector.
+ *
+ * <p>The `trino.jdbc.*` settings are not propagated to the dynamic catalogs, so starting the
+ * manager from a dynamic connector would make the internal JDBC connection lose its credentials and
+ * TLS settings.
+ */
+public class TestGravitinoConnectorFactoryStart {
+
+  // Nothing listens on this port, but the Trino driver connects lazily, so the register still
+  // initializes successfully.
+  private static final String COORDINATOR_URI = "http://127.0.0.1:1";
+
+  @TempDir private static Path catalogStoreDir;
+
+  private static Map<String, String> staticConfig() {
+    Map<String, String> config = new HashMap<>();
+    config.put("gravitino.metalake", "test");
+    config.put("discovery.uri", COORDINATOR_URI);
+    config.put("catalog.config-dir", catalogStoreDir.toString());
+    config.put("trino.jdbc.user", "gravitino");
+    return config;
+  }
+
+  private static Map<String, String> dynamicConfig() {
+    Map<String, String> config = new HashMap<>();
+    config.put("gravitino.metalake", "test");
+    // A dynamic catalog config carries neither `discovery.uri` nor any `trino.jdbc.*` setting.
+    config.put(GravitinoConfig.GRAVITINO_DYNAMIC_CONNECTOR, "true");
+    config.put(GravitinoConfig.GRAVITINO_DYNAMIC_CONNECTOR_CATALOG_CONFIG, "{}");
+    return config;
+  }
+
+  private static ConnectorContext mockContext() {
+    ConnectorContext context = mock(ConnectorContext.class);
+    when(context.getSpiVersion()).thenReturn("478");
+    return context;
+  }
+
+  /** A factory that always reports itself as running on the coordinator. */
+  private static class CoordinatorFactory extends GravitinoConnectorFactory {
+    CoordinatorFactory(GravitinoAdminClient client) {
+      super(client);
+    }
+
+    @Override
+    protected boolean isCoordinator(ConnectorContext connectorContext) {
+      return true;
+    }
+  }
+
+  private static CoordinatorFactory newFactory() {
+    return new CoordinatorFactory(mock(GravitinoAdminClient.class));
+  }
+
+  @Test
+  public void testStaticConnectorStartsTheManager() {
+    CoordinatorFactory factory = newFactory();
+
+    assertNotNull(factory.create("gravitino", staticConfig(), mockContext()));
+    assertTrue(factory.isCatalogConnectorManagerStartTriggered());
+  }
+
+  @Test
+  public void testDynamicConnectorDoesNotStartTheManager() {
+    CoordinatorFactory factory = newFactory();
+
+    Exception e =
+        assertThrows(
+            Exception.class, () -> factory.create("catalog", dynamicConfig(), mockContext()));
+
+    // It fails later while building the dynamic catalog, never by connecting back to Trino.
+    assertFalse(
+        e.getMessage().contains("jdbc:trino://"),
+        "The manager must not be started from a dynamic connector, got: " + e.getMessage());
+    assertNotNull(factory.getCatalogConnectorManager());
+    assertFalse(factory.isCatalogConnectorManagerStartTriggered());
+  }
+
+  @Test
+  public void testStaticConnectorStartsTheManagerAfterADynamicOne() {
+    CoordinatorFactory factory = newFactory();
+
+    // The coordinator restarted and Trino loaded a Gravitino-created catalog first.
+    assertThrows(Exception.class, () -> factory.create("catalog", dynamicConfig(), mockContext()));
+
+    // The static catalog is loaded afterwards and must start the manager with its own config.
+    // Had the dynamic config been used instead, `discovery.uri` would have been missing and the
+    // register would have failed to build the JDBC URI.
+    assertNotNull(factory.create("gravitino", staticConfig(), mockContext()));
+    assertTrue(factory.isCatalogConnectorManagerStartTriggered());
+  }
+
+  @Test
+  public void testStartIsAttemptedOnlyOnce() {
+    CoordinatorFactory factory = newFactory();
+
+    Map<String, String> brokenConfig = staticConfig();
+    brokenConfig.put("catalog.config-dir", "/not/exists/catalog");
+    assertThrows(Exception.class, () -> factory.create("gravitino", brokenConfig, mockContext()));
+
+    // Everything that makes start() fail is a configuration error, so the next create() must not
+    // try again: a second init() would open another connection and abandon the first one.
+    assertNotNull(factory.create("gravitino", brokenConfig, mockContext()));
+  }
+
+  @Test
+  public void testDynamicConfigCarriesNoJdbcSettings() {
+    GravitinoConfig config = new GravitinoConfig(ImmutableMap.copyOf(staticConfig()));
+
+    // What a dynamic catalog would receive: no `trino.jdbc.*`, no `discovery.uri`.
+    String catalogConfig = config.toCatalogConfig();
+    assertFalse(catalogConfig.contains("trino.jdbc."));
+    assertFalse(catalogConfig.contains("discovery.uri"));
+  }
+}
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java
new file mode 100644
index 0000000000..2effd98843
--- /dev/null
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/TestCatalogRegister.java
@@ -0,0 +1,380 @@
+/*
+ * 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.trino.connector.catalog;
+
+import static org.apache.gravitino.trino.connector.GravitinoErrorCode.GRAVITINO_ILLEGAL_ARGUMENT;
+import static org.apache.gravitino.trino.connector.GravitinoErrorCode.GRAVITINO_MISSING_CONFIG;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+import io.trino.spi.TrinoException;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+import org.apache.gravitino.trino.connector.GravitinoConfig;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.io.TempDir;
+
+public class TestCatalogRegister {
+
+  @TempDir private static Path tempDir;
+
+  private static GravitinoConfig config(Map<String, String> extraConfig) {
+    Map<String, String> configMap = new HashMap<>();
+    configMap.put("gravitino.metalake", "test");
+    configMap.put("discovery.uri", "http://localhost:8080");
+    configMap.putAll(extraConfig);
+    return new GravitinoConfig(configMap);
+  }
+
+  private static Path createStoreFile() throws IOException {
+    return Files.createTempFile(tempDir, "store", ".jks");
+  }
+
+  @Test
+  public void testDefaultProperties() {
+    Properties properties = CatalogRegister.buildJdbcProperties(config(Map.of()));
+
+    assertEquals("admin", properties.get("user"));
+    // An empty password must not be sent to the driver.
+    assertNull(properties.get("password"));
+    assertNull(properties.get("SSL"));
+    assertNull(properties.get("roles"));
+  }
+
+  @Test
+  public void testPasswordIsSetWhenNotEmpty() {
+    Properties properties =
+        CatalogRegister.buildJdbcProperties(
+            config(Map.of("trino.jdbc.user", "gravitino", "trino.jdbc.password", "secret")));
+
+    assertEquals("gravitino", properties.get("user"));
+    assertEquals("secret", properties.get("password"));
+  }
+
+  @Test
+  public void testHttpsDiscoveryUriWithTruststore() throws IOException {
+    String truststore = createStoreFile().toString();
+    Properties properties =
+        CatalogRegister.buildJdbcProperties(
+            config(
+                Map.of(
+                    "discovery.uri", "https://localhost:8443",
+                    "trino.jdbc.ssl.truststore.path", truststore,
+                    "trino.jdbc.ssl.truststore.password", "truststore-secret",
+                    "trino.jdbc.ssl.truststore.type", "PKCS12")));
+
+    assertEquals("true", properties.get("SSL"));
+    assertEquals("FULL", properties.get("SSLVerification"));
+    assertEquals(truststore, properties.get("SSLTrustStorePath"));
+    assertEquals("truststore-secret", properties.get("SSLTrustStorePassword"));
+    assertEquals("PKCS12", properties.get("SSLTrustStoreType"));
+  }
+
+  @Test
+  public void testSslEnabledDerivedFromDiscoveryUri() {
+    GravitinoConfig config = config(Map.of("discovery.uri", "https://localhost:8443"));
+    assertTrue(config.isTrinoJdbcSslEnabled());
+
+    Properties properties = CatalogRegister.buildJdbcProperties(config);
+    assertEquals("true", properties.get("SSL"));
+    assertEquals("FULL", properties.get("SSLVerification"));
+    // Without a configured truststore the driver falls back to the default JVM truststore.
+    assertNull(properties.get("SSLTrustStorePath"));
+  }
+
+  @Test
+  public void testExplicitSslEnabledOverridesDiscoveryUri() {
+    GravitinoConfig config =
+        config(
+            Map.of("discovery.uri", "https://localhost:8443", "trino.jdbc.ssl.enabled", "false"));
+    assertFalse(config.isTrinoJdbcSslEnabled());
+    assertNull(CatalogRegister.buildJdbcProperties(config).get("SSL"));
+  }
+
+  @Test
+  public void testSslEnabledIgnoresSurroundingWhitespace() {
+    GravitinoConfig config = config(Map.of("trino.jdbc.ssl.enabled", " true "));
+    assertTrue(config.isTrinoJdbcSslEnabled());
+    assertEquals("true", CatalogRegister.buildJdbcProperties(config).get("SSL"));
+  }
+
+  @Test
+  public void testSslVerificationIsNormalized() {
+    Properties properties =
+        CatalogRegister.buildJdbcProperties(
+            config(
+                Map.of("trino.jdbc.ssl.enabled", "true", "trino.jdbc.ssl.verification", " none ")));
+
+    assertEquals("NONE", properties.get("SSLVerification"));
+  }
+
+  @Test
+  public void testRoles() {
+    Properties properties =
+        CatalogRegister.buildJdbcProperties(config(Map.of("trino.jdbc.roles", "system:sysadmin")));
+
+    assertEquals("system:sysadmin", properties.get("roles"));
+  }
+
+  @Test
+  public void testExtraPropertiesArePassedThroughAndOverride() {
+    Properties properties =
+        CatalogRegister.buildJdbcProperties(
+            config(
+                Map.of(
+                    "trino.jdbc.ssl.enabled", "true",
+                    "trino.jdbc.properties.KerberosRemoteServiceName", "trino",
+                    "trino.jdbc.properties.SSLVerification", "CA")));
+
+    assertEquals("trino", properties.get("KerberosRemoteServiceName"));
+    // The escape hatch wins over the value derived from the dedicated configuration.
+    assertEquals("CA", properties.get("SSLVerification"));
+  }
+
+  @Test
+  public void testHttpsDiscoveryUriWithKeystore() throws IOException {
+    String keystore = createStoreFile().toString();
+    Properties properties =
+        CatalogRegister.buildJdbcProperties(
+            config(
+                Map.of(
+                    "discovery.uri", "https://localhost:8443",
+                    "trino.jdbc.ssl.keystore.path", keystore,
+                    "trino.jdbc.ssl.keystore.password", "keystore-secret",
+                    "trino.jdbc.ssl.keystore.type", "PKCS12")));
+
+    assertEquals(keystore, properties.get("SSLKeyStorePath"));
+    assertEquals("keystore-secret", properties.get("SSLKeyStorePassword"));
+    assertEquals("PKCS12", properties.get("SSLKeyStoreType"));
+  }
+
+  @Test
+  public void testKeystoreWithoutSslEnabled() throws IOException {
+    TrinoException e =
+        assertThrows(
+            TrinoException.class,
+            () ->
+                CatalogRegister.buildJdbcProperties(
+                    config(Map.of("trino.jdbc.ssl.keystore.path", createStoreFile().toString()))));
+
+    assertEquals(GRAVITINO_ILLEGAL_ARGUMENT.toErrorCode(), e.getErrorCode());
+    assertTrue(e.getMessage().contains("trino.jdbc.ssl.keystore.path"));
+  }
+
+  @Test
+  public void testKeystorePasswordWithoutKeystorePath() {
+    TrinoException e =
+        assertThrows(
+            TrinoException.class,
+            () ->
+                CatalogRegister.buildJdbcProperties(
+                    config(
+                        Map.of(
+                            "trino.jdbc.ssl.enabled", "true",
+                            "trino.jdbc.ssl.keystore.password", "keystore-secret"))));
+
+    assertEquals(GRAVITINO_ILLEGAL_ARGUMENT.toErrorCode(), e.getErrorCode());
+    assertTrue(e.getMessage().contains("trino.jdbc.ssl.keystore.path"));
+  }
+
+  @Test
+  public void testKeystoreFileNotFound() {
+    TrinoException e =
+        assertThrows(
+            TrinoException.class,
+            () ->
+                CatalogRegister.buildJdbcProperties(
+                    config(
+                        Map.of(
+                            "trino.jdbc.ssl.enabled", "true",
+                            "trino.jdbc.ssl.keystore.path", "/not/exists/keystore.p12"))));
+
+    assertEquals(GRAVITINO_MISSING_CONFIG.toErrorCode(), e.getErrorCode());
+    assertTrue(e.getMessage().contains("does not exist"));
+  }
+
+  @Test
+  public void testKeystoreWithVerificationNone() throws IOException {
+    TrinoException e =
+        assertThrows(
+            TrinoException.class,
+            () ->
+                CatalogRegister.buildJdbcProperties(
+                    config(
+                        Map.of(
+                            "trino.jdbc.ssl.enabled", "true",
+                            "trino.jdbc.ssl.verification", "NONE",
+                            "trino.jdbc.ssl.keystore.path", createStoreFile().toString()))));
+
+    assertEquals(GRAVITINO_ILLEGAL_ARGUMENT.toErrorCode(), e.getErrorCode());
+    assertTrue(e.getMessage().contains("NONE"));
+    assertTrue(e.getMessage().contains("trino.jdbc.ssl.keystore.path"));
+  }
+
+  @Test
+  public void testInvalidSslVerification() {
+    TrinoException e =
+        assertThrows(
+            TrinoException.class,
+            () ->
+                CatalogRegister.buildJdbcProperties(
+                    config(
+                        Map.of(
+                            "trino.jdbc.ssl.enabled", "true",
+                            "trino.jdbc.ssl.verification", "PARTIAL"))));
+
+    assertEquals(GRAVITINO_ILLEGAL_ARGUMENT.toErrorCode(), e.getErrorCode());
+    assertTrue(e.getMessage().contains("trino.jdbc.ssl.verification"));
+  }
+
+  @Test
+  public void testSslVerificationWithoutSslEnabled() {
+    TrinoException e =
+        assertThrows(
+            TrinoException.class,
+            () ->
+                CatalogRegister.buildJdbcProperties(
+                    config(Map.of("trino.jdbc.ssl.verification", "NONE"))));
+
+    assertEquals(GRAVITINO_ILLEGAL_ARGUMENT.toErrorCode(), e.getErrorCode());
+    assertTrue(e.getMessage().contains("trino.jdbc.ssl.enabled"));
+  }
+
+  @Test
+  public void testTruststoreWithoutSslEnabled() throws IOException {
+    TrinoException e =
+        assertThrows(
+            TrinoException.class,
+            () ->
+                CatalogRegister.buildJdbcProperties(
+                    config(
+                        Map.of("trino.jdbc.ssl.truststore.path", createStoreFile().toString()))));
+
+    assertEquals(GRAVITINO_ILLEGAL_ARGUMENT.toErrorCode(), e.getErrorCode());
+    assertTrue(e.getMessage().contains("trino.jdbc.ssl.truststore.path"));
+  }
+
+  @Test
+  public void testTruststorePasswordWithoutSslEnabled() {
+    TrinoException e =
+        assertThrows(
+            TrinoException.class,
+            () ->
+                CatalogRegister.buildJdbcProperties(
+                    config(Map.of("trino.jdbc.ssl.truststore.password", "truststore-secret"))));
+
+    assertEquals(GRAVITINO_ILLEGAL_ARGUMENT.toErrorCode(), e.getErrorCode());
+    assertTrue(e.getMessage().contains("trino.jdbc.ssl.truststore.password"));
+  }
+
+  @Test
+  public void testTruststoreTypeWithoutSslEnabled() {
+    TrinoException e =
+        assertThrows(
+            TrinoException.class,
+            () ->
+                CatalogRegister.buildJdbcProperties(
+                    config(Map.of("trino.jdbc.ssl.truststore.type", "PKCS12"))));
+
+    assertEquals(GRAVITINO_ILLEGAL_ARGUMENT.toErrorCode(), e.getErrorCode());
+    assertTrue(e.getMessage().contains("trino.jdbc.ssl.truststore.type"));
+  }
+
+  @Test
+  public void testBlankSslVerificationFallsBackToDefault() {
+    Properties properties =
+        CatalogRegister.buildJdbcProperties(
+            config(Map.of("trino.jdbc.ssl.enabled", "true", "trino.jdbc.ssl.verification", "")));
+
+    assertEquals("FULL", properties.get("SSLVerification"));
+  }
+
+  @Test
+  public void testTruststorePasswordWithoutTruststorePath() {
+    TrinoException e =
+        assertThrows(
+            TrinoException.class,
+            () ->
+                CatalogRegister.buildJdbcProperties(
+                    config(
+                        Map.of(
+                            "trino.jdbc.ssl.enabled", "true",
+                            "trino.jdbc.ssl.truststore.password", "truststore-secret"))));
+
+    assertEquals(GRAVITINO_ILLEGAL_ARGUMENT.toErrorCode(), e.getErrorCode());
+    assertTrue(e.getMessage().contains("trino.jdbc.ssl.truststore.path"));
+  }
+
+  @Test
+  public void testTruststoreTypeWithoutTruststorePath() {
+    TrinoException e =
+        assertThrows(
+            TrinoException.class,
+            () ->
+                CatalogRegister.buildJdbcProperties(
+                    config(
+                        Map.of(
+                            "trino.jdbc.ssl.enabled", "true",
+                            "trino.jdbc.ssl.truststore.type", "PKCS12"))));
+
+    assertEquals(GRAVITINO_ILLEGAL_ARGUMENT.toErrorCode(), e.getErrorCode());
+    assertTrue(e.getMessage().contains("trino.jdbc.ssl.truststore.path"));
+  }
+
+  @Test
+  public void testTruststoreWithVerificationNone() throws IOException {
+    TrinoException e =
+        assertThrows(
+            TrinoException.class,
+            () ->
+                CatalogRegister.buildJdbcProperties(
+                    config(
+                        Map.of(
+                            "trino.jdbc.ssl.enabled", "true",
+                            "trino.jdbc.ssl.verification", "NONE",
+                            "trino.jdbc.ssl.truststore.path", createStoreFile().toString()))));
+
+    assertEquals(GRAVITINO_ILLEGAL_ARGUMENT.toErrorCode(), e.getErrorCode());
+    assertTrue(e.getMessage().contains("NONE"));
+  }
+
+  @Test
+  public void testTruststoreFileNotFound() {
+    TrinoException e =
+        assertThrows(
+            TrinoException.class,
+            () ->
+                CatalogRegister.buildJdbcProperties(
+                    config(
+                        Map.of(
+                            "trino.jdbc.ssl.enabled", "true",
+                            "trino.jdbc.ssl.truststore.path", "/not/exists/truststore.jks"))));
+
+    assertEquals(GRAVITINO_MISSING_CONFIG.toErrorCode(), e.getErrorCode());
+    assertTrue(e.getMessage().contains("does not exist"));
+    assertTrue(e.getMessage().contains("trino.jdbc.ssl.truststore.path"));
+  }
+}


(gravitino) 04/13: [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Route lakehouse-iceberg catalogs through the Iceberg REST server

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diqiu50 pushed a commit to branch trino-irc-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit f1beaf7b97c3bf29fe10cc839e1890a80ab33180
Author: diqiu50 <di...@apache.org>
AuthorDate: Fri Aug 21 18:16:08 2026 +0800

    [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Route lakehouse-iceberg catalogs through the Iceberg REST server
    
    (cherry picked from commit 859ad4c82049c29099c90298f3f51085042d4b83)
---
 docs/trino-connector/authentication.md             |  20 +-
 docs/trino-connector/catalog-iceberg.md            |  79 +++++++
 docs/trino-connector/configuration.md              |  11 +
 .../docker-script/docker-compose.yaml              |   2 +
 .../init/trino/config/catalog/gravitino.properties |   1 +
 .../docker-script/init/trino/init.sh               |   3 +
 .../integration/test/container/ContainerSuite.java |   2 +
 .../test/container/TrinoITContainers.java          |   6 +-
 .../gravitino/integration/test/util/BaseIT.java    |  22 ++
 trino-connector/integration-test/build.gradle.kts  |   1 +
 .../integration/test/TrinoConnectorIT.java         |  19 ++
 .../integration/test/TrinoQueryITBase.java         |  13 ++
 .../gravitino/trino/connector/GravitinoConfig.java |  76 ++++++-
 .../catalog/DefaultCatalogConnectorFactory.java    |   2 +-
 .../iceberg/IcebergCatalogPropertyConverter.java   | 120 +++++++++-
 .../catalog/iceberg/IcebergConnectorAdapter.java   |  29 ++-
 .../trino/connector/TestGravitinoConfig.java       |  53 +++++
 .../TestIcebergCatalogPropertyConverter.java       | 253 ++++++++++++++++++++-
 18 files changed, 696 insertions(+), 16 deletions(-)

diff --git a/docs/trino-connector/authentication.md b/docs/trino-connector/authentication.md
index 9793e7749f..322eef9f5d 100644
--- a/docs/trino-connector/authentication.md
+++ b/docs/trino-connector/authentication.md
@@ -193,7 +193,25 @@ Whether the coordinator can populate this extra-credential depends on the Trino
 
 The `gravitino.client.oauth2.*` properties above still configure the shared bootstrap/admin client used for catalog discovery — they are unrelated to the per-user forwarded token.
 
-For an Iceberg catalog with `catalog-backend=rest` (backed by an Iceberg REST Catalog), the connector does not set `iceberg.rest-catalog.security`/`iceberg.rest-catalog.session` on its own — that catalog's own `gravitino.client.*` config is unrelated to how its underlying Iceberg REST catalog authenticates. To also forward the end user's token to the REST catalog itself, set `trino.bypass.iceberg.rest-catalog.security=OAUTH2` and `trino.bypass.iceberg.rest-catalog.session=USER` explicitl [...]
+For an Iceberg catalog reached through the Gravitino Iceberg REST server (IRC) — every
+`lakehouse-iceberg` catalog, unless `gravitino.iceberg.rest-enabled=false`; see [Iceberg
+catalog](./catalog-iceberg.md#how-trino-reaches-the-catalog) — the IRC's own authentication is
+configured once per Trino cluster with the `gravitino.iceberg.rest-catalog.` prefix, and
+`iceberg.rest-catalog.session=USER` is set automatically when `forwardUser=true`:
+
+```properties
+gravitino.iceberg.rest-uri=http://gravitino-host:9001/iceberg
+gravitino.iceberg.rest-catalog.security=OAUTH2
+gravitino.iceberg.rest-catalog.oauth2.credential=service-account-id:service-account-secret
+gravitino.iceberg.rest-catalog.oauth2.server-uri=http://your-idp/realms/gravitino/protocol/openid-connect/token
+gravitino.iceberg.rest-catalog.oauth2.scope=email
+```
+
+This is a completely separate credential from the one the connector uses against the main Gravitino
+server; it is not reused automatically.
+
+For an Iceberg catalog with `catalog-backend=rest` (pointing at an Iceberg REST Catalog of its own,
+which the connector does not re-route), the connector does not set `iceberg.rest-catalog.security`/`iceberg.rest-catalog.session` on its own — that catalog's own `gravitino.client.*` config is unrelated to how its underlying Iceberg REST catalog authenticates. To also forward the end user's token to the REST catalog itself, set `trino.bypass.iceberg.rest-catalog.security=OAUTH2` and `trino.bypass.iceberg.rest-catalog.session=USER` explicitly on that catalog's properties, alongside its bo [...]
 
 **Configuration properties:**
 
diff --git a/docs/trino-connector/catalog-iceberg.md b/docs/trino-connector/catalog-iceberg.md
index fbecbcb7d0..223b597fe9 100644
--- a/docs/trino-connector/catalog-iceberg.md
+++ b/docs/trino-connector/catalog-iceberg.md
@@ -20,6 +20,85 @@ To use Iceberg, you need:
   - ORC
   - Parquet (default)
 
+## How Trino Reaches the Catalog
+
+The Gravitino Trino connector loads every `lakehouse-iceberg` catalog through the Gravitino Iceberg
+REST server (IRC), regardless of the catalog's `catalog-backend`. `catalog-backend` describes how
+Gravitino stores the catalog's metadata; it does not decide how the query engine reaches the data.
+
+This is what makes [credential vending](../security/credential-vending.md) work. Trino only consumes
+vended credentials in its `rest` Iceberg catalog type — the `jdbc` and `hive_metastore` types have
+nowhere to put the session token of an STS temporary credential — so a catalog with
+`credential-providers=s3-token` produces no usable credential on those paths. Routing through the
+IRC means every table access gets a freshly issued temporary credential over the Iceberg REST
+protocol.
+
+Configure the IRC endpoint once per Trino cluster, in `etc/catalog/gravitino.properties`:
+
+```properties
+connector.name=gravitino
+gravitino.metalake=test
+gravitino.uri=http://gravitino-host:8090
+
+gravitino.iceberg.rest-uri=http://gravitino-host:9001/iceberg
+```
+
+The endpoint is deployment topology, not a property of the data source, so it does not belong on the
+catalog: it would have to be repeated on every new catalog, moving the IRC would mean editing all of
+them, and one catalog could not serve two Trino clusters that reach the IRC by different hostnames.
+
+The connector derives everything else from the catalog itself. The Gravitino catalog name is passed
+as both `iceberg.rest-catalog.warehouse` and `iceberg.rest-catalog.prefix` — the Iceberg client
+selects the catalog twice over, first as the query parameter of the `GET /v1/config` call that
+discovers it, then as the path segment of every request after that. The Trino native file system
+(`fs.native-s3.enabled` and `s3.region`, or the GCS and Azure equivalents) is derived from the
+catalog's `warehouse` scheme and storage properties.
+
+On the Gravitino side, the IRC must run with the dynamic config provider so it can serve catalogs
+defined in Gravitino:
+
+```properties
+gravitino.auxService.names = iceberg-rest
+gravitino.iceberg-rest.catalog-config-provider = dynamic-config-provider
+gravitino.iceberg-rest.gravitino-metalake = test
+```
+
+### Authenticating to the Iceberg REST Server
+
+If the IRC has authentication enabled, the internal Iceberg REST catalog that the connector builds
+must authenticate to it on its own. This is a separate credential from the one the connector uses
+against the main Gravitino server, and it is not reused automatically. Any property prefixed with
+`gravitino.iceberg.rest-catalog.` is passed through to the internal catalog with the prefix
+rewritten to `iceberg.rest-catalog.`:
+
+```properties
+gravitino.iceberg.rest-catalog.security=OAUTH2
+gravitino.iceberg.rest-catalog.oauth2.credential=client_id:client_secret
+gravitino.iceberg.rest-catalog.oauth2.server-uri=http://your-idp/token
+gravitino.iceberg.rest-catalog.oauth2.scope=email
+```
+
+Omitting this block against an authenticated IRC surfaces as an authentication error rather than a
+missing-configuration error, which is easy to misdiagnose.
+
+When `gravitino.client.session.forwardUser=true`, the connector also sets
+`iceberg.rest-catalog.session=USER` so that each query carries the end user's identity to the IRC,
+keeping per-user credential vending and per-user authorization intact. Set
+`gravitino.iceberg.rest-catalog.session` explicitly to override it. See
+[Authentication](./authentication.md) for the full setup.
+
+### Limitations
+
+- One IRC serves exactly one metalake, fixed at startup by
+  `gravitino.iceberg-rest.gravitino-metalake`. In multi-metalake mode
+  (`gravitino.use-single-metalake=false`), only catalogs in that metalake are reachable; the others
+  fail on the IRC side with `NoSuchCatalogException`.
+- A catalog created with `catalog-backend=rest` keeps pointing at its own configured `uri` and is
+  not re-routed, since it already reaches an Iceberg REST catalog directly.
+- To disable this routing entirely — for a deployment that does not run the IRC — set
+  `gravitino.iceberg.rest-enabled=false`. Iceberg catalogs are then translated into Trino's `jdbc`
+  or `hive_metastore` catalog types as before, and credential vending does not work.
+
 ## Schema Operations
 
 ### Create a Schema
diff --git a/docs/trino-connector/configuration.md b/docs/trino-connector/configuration.md
index 5bcb98636e..0436de81c5 100644
--- a/docs/trino-connector/configuration.md
+++ b/docs/trino-connector/configuration.md
@@ -29,11 +29,22 @@ license: "This software is licensed under the Apache License version 2."
 | gravitino.client.                           | string  | (none)                | The configuration key prefix for the Gravitino client config.                                                                                                                                                                                                                                                                                    | No       |
 | gravitino.trino.skip-catalog-patterns       | string  | (none)                | The `gravitino.trino.skip-catalog-patterns` defines a comma-separated list of catalog name regex patterns that should be excluded from loading. For example, `test_.*, .*_tmp` excludes all catalogs starting with `test_` or ending with `_tmp`.                                                                                                | No       |
 | gravitino.use-single-metalake               | boolean | true                  | If `true`, only one metalake is used and catalogs are identified by `<catalog_name>`. If `false`, multi-metalake mode is enabled and catalogs are identified by `<metalake_name>.<catalog_name>`.                                                                                                                                                | No       |
+| gravitino.iceberg.rest-enabled              | boolean | true                  | If `true`, `lakehouse-iceberg` catalogs are loaded through the Gravitino Iceberg REST server (IRC) instead of being translated into Trino's `jdbc` or `hive_metastore` Iceberg catalog type. This is what makes credential vending work. Requires `gravitino.iceberg.rest-uri`. Set to `false` for a deployment that does not run the IRC.                                    | No       |
+| gravitino.iceberg.rest-uri                  | string  | (none)                | The endpoint of the Gravitino Iceberg REST server, for example `http://gravitino-host:9001/iceberg`. Required when `gravitino.iceberg.rest-enabled` is `true` and the metalake contains `lakehouse-iceberg` catalogs.                                                                                               | No       |
+| gravitino.iceberg.rest-catalog.             | string  | (none)                | The configuration key prefix for properties passed through to the internal Trino Iceberg REST catalog. The prefix is rewritten to `iceberg.rest-catalog.`, so `gravitino.iceberg.rest-catalog.security=OAUTH2` becomes `iceberg.rest-catalog.security=OAUTH2`.                                                      | No       |
 
 To configure the Gravitino client, use properties prefixed with `gravitino.client.`. These properties will directly passed to the Gravitino client.
 
 **Note:** Invalid configuration properties will result in exceptions. Please see [Gravitino Java client configurations](../how-to-use-gravitino-client.md#java-client-configuration) for more support client configuration.
 
+:::caution
+`gravitino.iceberg.rest-enabled` defaults to `true`. When upgrading an existing deployment whose
+metalake contains `lakehouse-iceberg` catalogs with `catalog-backend=jdbc` or `hive`, those catalogs
+fail to load unless you either set `gravitino.iceberg.rest-uri` to your Iceberg REST server endpoint,
+or set `gravitino.iceberg.rest-enabled=false` to keep the previous behavior. See
+[Iceberg catalog](./catalog-iceberg.md#how-trino-reaches-the-catalog).
+:::
+
 Multi-metalake mode (`gravitino.use-single-metalake=false`) is supported on Trino connector versions 435-445 and 469-478. On versions 446-468, a warning is logged and the connector initializes, but the mode is not fully supported and some operations may fail.
 
 ## Connecting to a TLS-enabled coordinator
diff --git a/integration-test-common/docker-script/docker-compose.yaml b/integration-test-common/docker-script/docker-compose.yaml
index 3ed57d07ca..1dfb8f5a7d 100644
--- a/integration-test-common/docker-script/docker-compose.yaml
+++ b/integration-test-common/docker-script/docker-compose.yaml
@@ -87,6 +87,7 @@ services:
       - HADOOP_USER_NAME=anonymous
       - GRAVITINO_HOST_IP=host.docker.internal
       - GRAVITINO_HOST_PORT=${GRAVITINO_SERVER_PORT:-8090}
+      - GRAVITINO_ICEBERG_REST_PORT=${GRAVITINO_ICEBERG_REST_PORT:-9001}
       - GRAVITINO_METALAKE_NAME=test
       - HIVE_HOST_IP=hive
       - TRINO_WORKER_NUM=${TRINO_WORKER_NUM:-0}
@@ -122,6 +123,7 @@ services:
       - HADOOP_USER_NAME=anonymous
       - GRAVITINO_HOST_IP=host.docker.internal
       - GRAVITINO_HOST_PORT=${GRAVITINO_SERVER_PORT:-8090}
+      - GRAVITINO_ICEBERG_REST_PORT=${GRAVITINO_ICEBERG_REST_PORT:-9001}
       - GRAVITINO_METALAKE_NAME=test
       - HIVE_HOST_IP=hive
       - TRINO_ROLE=worker
diff --git a/integration-test-common/docker-script/init/trino/config/catalog/gravitino.properties b/integration-test-common/docker-script/init/trino/config/catalog/gravitino.properties
index 08789c84c0..d38c18c458 100644
--- a/integration-test-common/docker-script/init/trino/config/catalog/gravitino.properties
+++ b/integration-test-common/docker-script/init/trino/config/catalog/gravitino.properties
@@ -20,6 +20,7 @@
 connector.name = gravitino
 gravitino.uri = http://GRAVITINO_HOST_IP:GRAVITINO_HOST_PORT
 gravitino.metalake = GRAVITINO_METALAKE_NAME
+gravitino.iceberg.rest-uri = http://GRAVITINO_ICEBERG_REST_HOST:GRAVITINO_ICEBERG_REST_PORT/iceberg
 gravitino.trino.skip-version-validation=true
 gravitino.client.authType = simple
 gravitino.client.session.forwardUser = true
diff --git a/integration-test-common/docker-script/init/trino/init.sh b/integration-test-common/docker-script/init/trino/init.sh
index 077c6f77d0..d713708e52 100644
--- a/integration-test-common/docker-script/init/trino/init.sh
+++ b/integration-test-common/docker-script/init/trino/init.sh
@@ -34,6 +34,9 @@ cp /usr/lib/trino/plugin/mysql/*mysql-connector-j-*.jar /usr/lib/trino/plugin/ic
 sed -i "s/GRAVITINO_HOST_IP:GRAVITINO_HOST_PORT/${GRAVITINO_HOST_IP}:${GRAVITINO_HOST_PORT}/g" /etc/trino/catalog/gravitino.properties
 # Update `gravitino.metalake = GRAVITINO_METALAKE_NAME` in the `conf/catalog/gravitino.properties`
 sed -i "s/GRAVITINO_METALAKE_NAME/${GRAVITINO_METALAKE_NAME}/g" /etc/trino/catalog/gravitino.properties
+# Update `gravitino.iceberg.rest-uri` in the `conf/catalog/gravitino.properties`. It uses its own
+# placeholders so that the substitution above cannot leave a half-replaced host behind.
+sed -i "s/GRAVITINO_ICEBERG_REST_HOST:GRAVITINO_ICEBERG_REST_PORT/${GRAVITINO_HOST_IP}:${GRAVITINO_ICEBERG_REST_PORT}/g" /etc/trino/catalog/gravitino.properties
 # Update `node.id=NODE_ID` in the `/conf/node.properties`
 sed -i "s/NODE_ID/${RANDOM}-${RANDOM}-${RANDOM}-${RANDOM}-${RANDOM}/g" /etc/trino/node.properties
 
diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.java
index b2b0ae50da..bc29a24e06 100644
--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.java
+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.java
@@ -288,6 +288,7 @@ public class ContainerSuite implements Closeable {
       String trinoConfDir,
       String trinoConnectorLibDir,
       int gravitinoServerPort,
+      int icebergRestServerPort,
       String metalakeName) {
     ITUtils.cleanDisk();
     if (trinoContainer == null) {
@@ -303,6 +304,7 @@ public class ContainerSuite implements Closeable {
                           .put("HADOOP_USER_NAME", "anonymous")
                           .put("GRAVITINO_HOST_IP", "host.docker.internal")
                           .put("GRAVITINO_HOST_PORT", String.valueOf(gravitinoServerPort))
+                          .put("GRAVITINO_ICEBERG_REST_PORT", String.valueOf(icebergRestServerPort))
                           .put("GRAVITINO_METALAKE_NAME", metalakeName)
                           .build())
                   .withNetwork(getNetwork())
diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/TrinoITContainers.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/TrinoITContainers.java
index a02e12de6a..14fe768c0b 100644
--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/TrinoITContainers.java
+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/TrinoITContainers.java
@@ -50,11 +50,12 @@ public class TrinoITContainers implements AutoCloseable {
   }
 
   public void launch(int gravitinoServerPort) throws Exception {
-    launch(gravitinoServerPort, "hive2", false, null, null, null);
+    launch(gravitinoServerPort, 0, "hive2", false, null, null, null);
   }
 
   public void launch(
       int gravitinoServerPort,
+      int icebergRestServerPort,
       String hiveRuntimeVersion,
       boolean isTrinoConnectorTest,
       Integer trinoWorkerNum,
@@ -81,6 +82,9 @@ public class TrinoITContainers implements AutoCloseable {
     }
     env.put("GRAVITINO_SERVER_PORT", String.valueOf(gravitinoServerPort));
     env.put("HIVE_RUNTIME_VERSION", hiveRuntimeVersion);
+    if (icebergRestServerPort > 0) {
+      env.put("GRAVITINO_ICEBERG_REST_PORT", String.valueOf(icebergRestServerPort));
+    }
     env.put("TRINO_CONNECTOR_TEST", String.valueOf(isTrinoConnectorTest));
     if (System.getProperty("gravitino.log.path") != null) {
       env.put("GRAVITINO_LOG_PATH", System.getProperty("gravitino.log.path"));
diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java
index 8c9cbfa510..f3a0724ef0 100644
--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java
+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/util/BaseIT.java
@@ -30,6 +30,7 @@ import com.google.common.collect.ImmutableMap;
 import java.io.File;
 import java.io.IOException;
 import java.lang.reflect.Field;
+import java.net.URI;
 import java.nio.charset.StandardCharsets;
 import java.nio.file.Files;
 import java.nio.file.Path;
@@ -674,6 +675,27 @@ public class BaseIT {
     return null;
   }
 
+  /**
+   * Enables the Iceberg REST auxiliary service before the server starts. Callers that hold a {@link
+   * BaseIT} instance rather than extending it use this instead of the protected fields.
+   *
+   * @param icebergRestConfigs extra server configs, typically the dynamic config provider and the
+   *     metalake the Iceberg REST service should serve
+   */
+  public void enableIcebergAuxRestService(Map<String, String> icebergRestConfigs) {
+    this.ignoreIcebergAuxRestService = false;
+    this.customConfigs.putAll(icebergRestConfigs);
+  }
+
+  /**
+   * Returns the port the Iceberg REST auxiliary service listens on.
+   *
+   * @return the Iceberg REST service port
+   */
+  public int getIcebergRestServicePort() {
+    return URI.create(getIcebergRestServiceUri()).getPort();
+  }
+
   protected String getIcebergRestServiceUri() {
     JettyServerConfig jettyServerConfig =
         JettyServerConfig.fromConfig(serverConfig, String.format("gravitino.iceberg-rest."));
diff --git a/trino-connector/integration-test/build.gradle.kts b/trino-connector/integration-test/build.gradle.kts
index f66c9e3649..c48e9719bf 100644
--- a/trino-connector/integration-test/build.gradle.kts
+++ b/trino-connector/integration-test/build.gradle.kts
@@ -34,6 +34,7 @@ dependencies {
   }
 
   testImplementation(project(":api"))
+  testImplementation(project(":catalogs:catalog-common"))
   testImplementation(project(":clients:client-java"))
   testImplementation(project(":common"))
   testImplementation(project(":core"))
diff --git a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java
index 10eb37db74..d0796e044f 100644
--- a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java
+++ b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoConnectorIT.java
@@ -23,6 +23,7 @@ import static org.testcontainers.shaded.org.awaitility.Awaitility.await;
 import com.google.common.collect.ImmutableMap;
 import com.google.common.collect.Maps;
 import com.google.common.collect.Sets;
+import java.net.URI;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
@@ -33,6 +34,7 @@ import java.util.concurrent.TimeUnit;
 import org.apache.gravitino.Catalog;
 import org.apache.gravitino.NameIdentifier;
 import org.apache.gravitino.Schema;
+import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
 import org.apache.gravitino.client.GravitinoMetalake;
 import org.apache.gravitino.integration.test.container.ContainerSuite;
 import org.apache.gravitino.integration.test.container.HiveContainer;
@@ -76,6 +78,8 @@ public class TrinoConnectorIT extends BaseIT {
 
   private static final ContainerSuite containerSuite = ContainerSuite.getInstance();
 
+  private static final String GRAVITINO_ICEBERG_REST_PREFIX = "gravitino.iceberg-rest.";
+
   public static String metalakeName =
       GravitinoITUtils.genRandomName("TrinoIT_metalake").toLowerCase();
   public static String catalogName =
@@ -90,6 +94,20 @@ public class TrinoConnectorIT extends BaseIT {
   private static GravitinoMetalake metalake;
   private static Catalog catalog;
 
+  @BeforeAll
+  @Override
+  public void startIntegrationTest() throws Exception {
+    // The Trino connector loads every lakehouse-iceberg catalog through the Iceberg REST server,
+    // so the auxiliary service has to run and serve this test's metalake.
+    ignoreIcebergAuxRestService = false;
+    customConfigs.put(
+        GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.ICEBERG_REST_CATALOG_CONFIG_PROVIDER,
+        IcebergConstants.DYNAMIC_ICEBERG_CATALOG_CONFIG_PROVIDER_NAME);
+    customConfigs.put(
+        GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_METALAKE, metalakeName);
+    super.startIntegrationTest();
+  }
+
   @BeforeAll
   public void startDockerContainer() throws TException, InterruptedException {
     String trinoConfDir = System.getenv("TRINO_CONF_DIR");
@@ -113,6 +131,7 @@ public class TrinoConnectorIT extends BaseIT {
         trinoConfDir,
         System.getenv("GRAVITINO_ROOT_DIR") + "/trino-connector/build/libs",
         getGravitinoServerPort(),
+        URI.create(getIcebergRestServiceUri()).getPort(),
         metalakeName);
     Assertions.assertTrue(
         containerSuite.getTrinoContainer().checkSyncCatalogFromGravitino(5, catalogName),
diff --git a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.java b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.java
index 5d955bca7e..24d33cbf2e 100644
--- a/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.java
+++ b/trino-connector/integration-test/src/test/java/org/apache/gravitino/trino/connector/integration/test/TrinoQueryITBase.java
@@ -20,6 +20,7 @@ package org.apache.gravitino.trino.connector.integration.test;
 
 import static java.lang.Thread.sleep;
 
+import com.google.common.collect.ImmutableMap;
 import java.io.File;
 import java.io.IOException;
 import java.nio.charset.StandardCharsets;
@@ -31,6 +32,7 @@ import org.apache.gravitino.Catalog;
 import org.apache.gravitino.NameIdentifier;
 import org.apache.gravitino.Namespace;
 import org.apache.gravitino.SupportsSchemas;
+import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
 import org.apache.gravitino.client.GravitinoAdminClient;
 import org.apache.gravitino.client.GravitinoMetalake;
 import org.apache.gravitino.exceptions.RESTException;
@@ -45,6 +47,8 @@ import org.slf4j.LoggerFactory;
 public class TrinoQueryITBase {
   private static final Logger LOG = LoggerFactory.getLogger(TrinoQueryITBase.class);
 
+  private static final String GRAVITINO_ICEBERG_REST_PREFIX = "gravitino.iceberg-rest.";
+
   // Auto start docker containers and Gravitino server
   protected static boolean autoStart = true;
 
@@ -87,6 +91,14 @@ public class TrinoQueryITBase {
   private void setEnv() throws Exception {
     baseIT = new BaseIT();
     if (autoStart) {
+      // The Trino connector loads every lakehouse-iceberg catalog through the Iceberg REST server,
+      // so the auxiliary service has to run and serve this test's metalake.
+      baseIT.enableIcebergAuxRestService(
+          ImmutableMap.of(
+              GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.ICEBERG_REST_CATALOG_CONFIG_PROVIDER,
+              IcebergConstants.DYNAMIC_ICEBERG_CATALOG_CONFIG_PROVIDER_NAME,
+              GRAVITINO_ICEBERG_REST_PREFIX + IcebergConstants.GRAVITINO_METALAKE,
+              metalakeName));
       baseIT.startIntegrationTest();
       gravitinoClient = baseIT.getGravitinoClient();
       gravitinoUri = String.format("http://127.0.0.1:%d", baseIT.getGravitinoServerPort());
@@ -108,6 +120,7 @@ public class TrinoQueryITBase {
 
       trinoITContainers.launch(
           baseIT.getGravitinoServerPort(),
+          baseIT.getIcebergRestServicePort(),
           hiveRuntimeVersion,
           isTrinoConnectorTest,
           trinoWorkerNum,
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
index 817d9f6306..e79645d0e6 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/GravitinoConfig.java
@@ -76,6 +76,9 @@ public class GravitinoConfig {
   public static final String GRAVITINO_DYNAMIC_CONNECTOR_CATALOG_CONFIG =
       "__gravitino.dynamic.connector.catalog.config";
 
+  /** The Trino Iceberg REST catalog property prefix. */
+  private static final String TRINO_ICEBERG_REST_CATALOG_PREFIX = "iceberg.rest-catalog.";
+
   private static final Map<String, ConfigEntry> CONFIG_DEFINITIONS = new HashMap<>();
   private final Map<String, String> config;
   private final List<Pattern> skipCatalogPatternList;
@@ -263,6 +266,32 @@ public class GravitinoConfig {
           "3600",
           false);
 
+  private static final ConfigEntry GRAVITINO_ICEBERG_REST_ENABLED =
+      new ConfigEntry(
+          "gravitino.iceberg.rest-enabled",
+          "When true, lakehouse-iceberg catalogs are loaded through the Gravitino Iceberg REST "
+              + "server instead of being translated into a Trino JDBC or Hive metastore Iceberg "
+              + "catalog. Requires gravitino.iceberg.rest-uri.",
+          "true",
+          false);
+
+  private static final ConfigEntry GRAVITINO_ICEBERG_REST_URI =
+      new ConfigEntry(
+          "gravitino.iceberg.rest-uri",
+          "The endpoint of the Gravitino Iceberg REST server, for example "
+              + "http://localhost:9001/iceberg.",
+          "",
+          false);
+
+  private static final ConfigEntry GRAVITINO_ICEBERG_REST_CATALOG_CONFIG_PREFIX =
+      new ConfigEntry(
+          "gravitino.iceberg.rest-catalog.",
+          "Prefix for properties passed through to the internal Trino Iceberg REST catalog. Any "
+              + "property beginning with this prefix is rewritten to iceberg.rest-catalog. and "
+              + "passed through (e.g., gravitino.iceberg.rest-catalog.security=OAUTH2).",
+          "",
+          false);
+
   /**
    * Constructs a new GravitinoConfig with the specified configuration.
    *
@@ -600,9 +629,13 @@ public class GravitinoConfig {
         stringList.add(String.format("\"%s\"='%s'", entry.getKey(), value));
       }
     }
-    // copy the configuration by the prefix of GRAVITINO_CLIENT_CONFIG_PREFIX
+    // copy the configuration by the prefix of GRAVITINO_CLIENT_CONFIG_PREFIX and
+    // GRAVITINO_ICEBERG_REST_CATALOG_CONFIG_PREFIX
     config.entrySet().stream()
-        .filter(entry -> entry.getKey().startsWith(GRAVITINO_CLIENT_CONFIG_PREFIX.key))
+        .filter(
+            entry ->
+                entry.getKey().startsWith(GRAVITINO_CLIENT_CONFIG_PREFIX.key)
+                    || entry.getKey().startsWith(GRAVITINO_ICEBERG_REST_CATALOG_CONFIG_PREFIX.key))
         .forEach(
             entry ->
                 stringList.add(String.format("\"%s\"='%s'", entry.getKey(), entry.getValue())));
@@ -678,6 +711,45 @@ public class GravitinoConfig {
     return parseLongConfigEntry(GRAVITINO_SESSION_CACHE_EXPIRE_AFTER_ACCESS_SECONDS);
   }
 
+  /**
+   * Returns whether lakehouse-iceberg catalogs are routed through the Gravitino Iceberg REST
+   * server.
+   *
+   * @return true if the Iceberg REST routing is enabled
+   */
+  public boolean isIcebergRestEnabled() {
+    return Boolean.parseBoolean(
+        config.getOrDefault(
+            GRAVITINO_ICEBERG_REST_ENABLED.key, GRAVITINO_ICEBERG_REST_ENABLED.defaultValue));
+  }
+
+  /**
+   * Retrieves the endpoint of the Gravitino Iceberg REST server.
+   *
+   * @return the Iceberg REST server endpoint, or an empty string if not configured
+   */
+  public String getIcebergRestUri() {
+    return config.getOrDefault(
+        GRAVITINO_ICEBERG_REST_URI.key, GRAVITINO_ICEBERG_REST_URI.defaultValue);
+  }
+
+  /**
+   * Retrieves the properties passed through to the internal Trino Iceberg REST catalog, with the
+   * {@code gravitino.iceberg.rest-catalog.} prefix rewritten to {@code iceberg.rest-catalog.}.
+   *
+   * @return the Trino Iceberg REST catalog properties
+   */
+  public Map<String, String> getIcebergRestCatalogConfig() {
+    String prefix = GRAVITINO_ICEBERG_REST_CATALOG_CONFIG_PREFIX.key;
+    return config.entrySet().stream()
+        .filter(entry -> entry.getKey().startsWith(prefix))
+        .collect(
+            Collectors.toMap(
+                entry ->
+                    TRINO_ICEBERG_REST_CATALOG_PREFIX + entry.getKey().substring(prefix.length()),
+                Map.Entry::getValue));
+  }
+
   private long parseLongConfigEntry(ConfigEntry entry) {
     String value = config.getOrDefault(entry.key, entry.defaultValue);
     try {
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/DefaultCatalogConnectorFactory.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/DefaultCatalogConnectorFactory.java
index 29b2979da2..66d6937d84 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/DefaultCatalogConnectorFactory.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/DefaultCatalogConnectorFactory.java
@@ -72,7 +72,7 @@ public class DefaultCatalogConnectorFactory implements CatalogConnectorFactory {
         new CatalogConnectorContext.Builder(new MemoryConnectorAdapter()));
     catalogBuilders.put(
         ICEBERG_CONNECTOR_PROVIDER_NAME,
-        new CatalogConnectorContext.Builder(new IcebergConnectorAdapter()));
+        new CatalogConnectorContext.Builder(new IcebergConnectorAdapter(config)));
     catalogBuilders.put(
         MYSQL_CONNECTOR_PROVIDER_NAME,
         new CatalogConnectorContext.Builder(new MySQLConnectorAdapter()));
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
index 7f5460cbf0..8073f1e1c2 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergCatalogPropertyConverter.java
@@ -22,16 +22,21 @@ package org.apache.gravitino.trino.connector.catalog.iceberg;
 import com.google.common.collect.Sets;
 import io.trino.spi.TrinoException;
 import java.util.HashMap;
+import java.util.Locale;
 import java.util.Map;
 import java.util.Set;
+import org.apache.commons.lang3.StringUtils;
 import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
 import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergPropertiesUtils;
 import org.apache.gravitino.credential.AzureAccountKeyCredential;
 import org.apache.gravitino.credential.Credential;
 import org.apache.gravitino.credential.JdbcCredential;
 import org.apache.gravitino.credential.S3SecretKeyCredential;
+import org.apache.gravitino.storage.S3Properties;
+import org.apache.gravitino.trino.connector.GravitinoConfig;
 import org.apache.gravitino.trino.connector.GravitinoErrorCode;
 import org.apache.gravitino.trino.connector.catalog.CatalogPropertyConverter;
+import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
 
 /**
  * A property converter for Iceberg catalogs that handles the conversion between Trino and Gravitino
@@ -46,6 +51,21 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
 
   private static final Set<String> REST_BACKEND_REQUIRED_PROPERTIES = Set.of("uri");
 
+  private static final String TRINO_ICEBERG_CATALOG_TYPE = "iceberg.catalog.type";
+  private static final String TRINO_ICEBERG_CATALOG_TYPE_REST = "rest";
+  private static final String TRINO_ICEBERG_REST_URI = "iceberg.rest-catalog.uri";
+  private static final String TRINO_ICEBERG_REST_PREFIX = "iceberg.rest-catalog.prefix";
+  private static final String TRINO_ICEBERG_REST_WAREHOUSE = "iceberg.rest-catalog.warehouse";
+  private static final String TRINO_ICEBERG_REST_VENDED_CREDENTIALS =
+      "iceberg.rest-catalog.vended-credentials-enabled";
+  private static final String TRINO_ICEBERG_REST_SESSION = "iceberg.rest-catalog.session";
+  private static final String TRINO_FS_HADOOP_ENABLED = "fs.hadoop.enabled";
+  private static final String TRINO_FS_NATIVE_S3_ENABLED = "fs.native-s3.enabled";
+  private static final String TRINO_FS_NATIVE_GCS_ENABLED = "fs.native-gcs.enabled";
+  private static final String TRINO_FS_NATIVE_AZURE_ENABLED = "fs.native-azure.enabled";
+  private static final String TRINO_S3_REGION = "s3.region";
+  private static final String TRINO_S3_ENDPOINT = "s3.endpoint";
+
   /**
    * Injects credentials from credential vending into the Iceberg catalog config. Applies JDBC
    * user/password for the JDBC backend and S3 credentials for S3-backed storage.
@@ -147,6 +167,102 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
     return jdbcProperties;
   }
 
+  /**
+   * Builds the Trino Iceberg connector config that reaches this catalog through the Gravitino
+   * Iceberg REST server, regardless of the catalog backend Gravitino uses to store its metadata.
+   *
+   * <p>This is the only path on which credential vending works: the Iceberg REST protocol issues a
+   * fresh temporary credential per table access, while Trino's jdbc and hive_metastore Iceberg
+   * catalog types have nowhere to put the session token of an STS credential.
+   *
+   * @param catalog the Gravitino catalog to load
+   * @param gravitinoConfig the connector configuration holding the Iceberg REST server endpoint
+   * @return the Trino Iceberg connector config
+   */
+  public Map<String, String> buildIcebergRestProperties(
+      GravitinoCatalog catalog, GravitinoConfig gravitinoConfig) {
+    String restUri = gravitinoConfig.getIcebergRestUri();
+    if (StringUtils.isBlank(restUri)) {
+      throw new TrinoException(
+          GravitinoErrorCode.GRAVITINO_MISSING_CONFIG,
+          "Missing required config 'gravitino.iceberg.rest-uri'. Set it to the Gravitino Iceberg "
+              + "REST server endpoint, for example http://localhost:9001/iceberg, or set "
+              + "'gravitino.iceberg.rest-enabled=false' to load Iceberg catalogs through their "
+              + "catalog backend instead.");
+    }
+
+    Map<String, String> config = new HashMap<>();
+    // The order of put operations determines the priority of parameters.
+    config.putAll(buildStorageProperties(catalog.getProperties()));
+    config.put(TRINO_ICEBERG_REST_VENDED_CREDENTIALS, "true");
+    if (gravitinoConfig.isForwardUser()) {
+      config.put(TRINO_ICEBERG_REST_SESSION, "USER");
+    }
+    // The catalog's own trino.bypass properties override the defaults above, so that a Trino
+    // release renaming one of them can be worked around without a connector change.
+    config.putAll(super.gravitinoToEngineProperties(catalog.getProperties()));
+    // The Iceberg REST server endpoint and its authentication are cluster-level operational
+    // settings, so they take precedence over anything set on a single catalog.
+    config.putAll(gravitinoConfig.getIcebergRestCatalogConfig());
+    config.put(TRINO_ICEBERG_CATALOG_TYPE, TRINO_ICEBERG_CATALOG_TYPE_REST);
+    config.put(TRINO_ICEBERG_REST_URI, restUri);
+    // The Iceberg client selects the catalog twice over: `warehouse` is the query parameter of the
+    // initial GET /v1/config that discovers the catalog, and `prefix` is the path segment of every
+    // request after it. Setting only the latter leaves the config call without a catalog name.
+    config.put(TRINO_ICEBERG_REST_WAREHOUSE, catalog.getName());
+    config.put(TRINO_ICEBERG_REST_PREFIX, catalog.getName());
+    return config;
+  }
+
+  /**
+   * Derives the Trino file system config from the catalog's warehouse location. Vended credentials
+   * are only consumed by Trino's native file systems, so the native implementation matching the
+   * warehouse scheme has to be enabled.
+   */
+  private Map<String, String> buildStorageProperties(Map<String, String> properties) {
+    Map<String, String> storageProperties = new HashMap<>();
+    storageProperties.put(TRINO_FS_HADOOP_ENABLED, "true");
+
+    String warehouse = properties.get(IcebergConstants.WAREHOUSE);
+    if (StringUtils.isBlank(warehouse)) {
+      return storageProperties;
+    }
+
+    String scheme = StringUtils.substringBefore(warehouse, "://").toLowerCase(Locale.ROOT);
+    switch (scheme) {
+      case "s3":
+      case "s3a":
+      case "s3n":
+        storageProperties.put(TRINO_FS_NATIVE_S3_ENABLED, "true");
+        copyProperty(
+            properties, S3Properties.GRAVITINO_S3_REGION, storageProperties, TRINO_S3_REGION);
+        copyProperty(
+            properties, S3Properties.GRAVITINO_S3_ENDPOINT, storageProperties, TRINO_S3_ENDPOINT);
+        break;
+      case "gs":
+        storageProperties.put(TRINO_FS_NATIVE_GCS_ENABLED, "true");
+        break;
+      case "abfs":
+      case "abfss":
+      case "wasb":
+      case "wasbs":
+        storageProperties.put(TRINO_FS_NATIVE_AZURE_ENABLED, "true");
+        break;
+      default:
+        // hdfs, file and any scheme without a Trino native file system stay on fs.hadoop.enabled.
+        break;
+    }
+    return storageProperties;
+  }
+
+  private void copyProperty(
+      Map<String, String> source, String sourceKey, Map<String, String> target, String targetKey) {
+    String value = source.get(sourceKey);
+    if (StringUtils.isNotBlank(value)) {
+      target.put(targetKey, value);
+    }
+  }
+
   private Map<String, String> buildRestBackendProperties(Map<String, String> properties) {
     Set<String> missingProperty =
         Sets.difference(REST_BACKEND_REQUIRED_PROPERTIES, properties.keySet());
@@ -157,8 +273,8 @@ public class IcebergCatalogPropertyConverter extends CatalogPropertyConverter {
     }
 
     Map<String, String> restProperties = new HashMap<>();
-    restProperties.put("iceberg.catalog.type", "rest");
-    restProperties.put("iceberg.rest-catalog.uri", properties.get(IcebergConstants.URI));
+    restProperties.put(TRINO_ICEBERG_CATALOG_TYPE, TRINO_ICEBERG_CATALOG_TYPE_REST);
+    restProperties.put(TRINO_ICEBERG_REST_URI, properties.get(IcebergConstants.URI));
     if (properties.containsKey(IcebergConstants.WAREHOUSE)) {
       restProperties.put(
           "iceberg.rest-catalog.warehouse", properties.get(IcebergConstants.WAREHOUSE));
diff --git a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java
index 8900775fb7..102c15d0f5 100644
--- a/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java
+++ b/trino-connector/trino-connector/src/main/java/org/apache/gravitino/trino/connector/catalog/iceberg/IcebergConnectorAdapter.java
@@ -24,8 +24,9 @@ import io.trino.spi.session.PropertyMetadata;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import org.apache.gravitino.catalog.property.PropertyConverter;
+import org.apache.gravitino.catalog.lakehouse.iceberg.IcebergConstants;
 import org.apache.gravitino.credential.Credential;
+import org.apache.gravitino.trino.connector.GravitinoConfig;
 import org.apache.gravitino.trino.connector.catalog.CatalogConnectorAdapter;
 import org.apache.gravitino.trino.connector.catalog.CatalogConnectorMetadataAdapter;
 import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
@@ -37,25 +38,41 @@ import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
 public class IcebergConnectorAdapter implements CatalogConnectorAdapter {
 
   private static final String CONNECTOR_ICEBERG = "iceberg";
+  private static final String REST_CATALOG_BACKEND = "rest";
+
   private final IcebergPropertyMeta propertyMetadata;
-  private final PropertyConverter catalogConverter;
+  private final IcebergCatalogPropertyConverter catalogConverter;
+  private final GravitinoConfig config;
 
   /**
    * Constructs a new IcebergConnectorAdapter. Initializes the property metadata and catalog
    * converter for handling Iceberg-specific configurations.
+   *
+   * @param config the Gravitino connector configuration
    */
-  public IcebergConnectorAdapter() {
+  public IcebergConnectorAdapter(GravitinoConfig config) {
     this.propertyMetadata = new IcebergPropertyMeta();
     this.catalogConverter = new IcebergCatalogPropertyConverter();
+    this.config = config;
   }
 
   @Override
   public Map<String, String> buildInternalConnectorConfig(
       GravitinoCatalog catalog, Credential[] credentials) throws Exception {
-    Map<String, String> config =
+    // The catalog backend describes how Gravitino stores the metadata; it does not decide how
+    // Trino reaches the data. Unless the routing is disabled, every catalog is loaded through the
+    // Gravitino Iceberg REST server, which is the only path that supports credential vending.
+    // A catalog that already has a REST backend keeps pointing at its own configured endpoint.
+    if (config.isIcebergRestEnabled()
+        && !REST_CATALOG_BACKEND.equals(
+            catalog.getProperty(IcebergConstants.CATALOG_BACKEND, null))) {
+      return catalogConverter.buildIcebergRestProperties(catalog, config);
+    }
+
+    Map<String, String> connectorConfig =
         new HashMap<>(catalogConverter.gravitinoToEngineProperties(catalog.getProperties()));
-    IcebergCatalogPropertyConverter.applyCredentials(credentials, config);
-    return config;
+    IcebergCatalogPropertyConverter.applyCredentials(credentials, connectorConfig);
+    return connectorConfig;
   }
 
   @Override
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
index 2d486b52c0..c31c594be0 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/TestGravitinoConfig.java
@@ -300,6 +300,59 @@ public class TestGravitinoConfig {
     assertTrue(config.isTrinoJdbcSslEnabled());
   }
 
+  @Test
+  public void testIcebergRestConfigDefaults() {
+    GravitinoConfig config = new GravitinoConfig(ImmutableMap.of("gravitino.metalake", "user_001"));
+
+    assertTrue(config.isIcebergRestEnabled());
+    assertEquals("", config.getIcebergRestUri());
+    assertTrue(config.getIcebergRestCatalogConfig().isEmpty());
+  }
+
+  @Test
+  public void testIcebergRestConfig() {
+    ImmutableMap<String, String> configMap =
+        ImmutableMap.of(
+            "gravitino.metalake",
+            "user_001",
+            "gravitino.iceberg.rest-enabled",
+            "false",
+            "gravitino.iceberg.rest-uri",
+            "http://127.0.0.1:9001/iceberg",
+            "gravitino.iceberg.rest-catalog.security",
+            "OAUTH2",
+            "gravitino.iceberg.rest-catalog.oauth2.credential",
+            "client_id:client_secret");
+    GravitinoConfig config = new GravitinoConfig(configMap);
+
+    assertFalse(config.isIcebergRestEnabled());
+    assertEquals("http://127.0.0.1:9001/iceberg", config.getIcebergRestUri());
+
+    Map<String, String> restCatalogConfig = config.getIcebergRestCatalogConfig();
+    assertEquals(2, restCatalogConfig.size());
+    assertEquals("OAUTH2", restCatalogConfig.get("iceberg.rest-catalog.security"));
+    assertEquals(
+        "client_id:client_secret", restCatalogConfig.get("iceberg.rest-catalog.oauth2.credential"));
+  }
+
+  @Test
+  public void testToCatalogConfigWithIcebergRestProperties() {
+    ImmutableMap<String, String> configMap =
+        ImmutableMap.of(
+            "gravitino.metalake",
+            "user_001",
+            "gravitino.iceberg.rest-uri",
+            "http://127.0.0.1:9001/iceberg",
+            "gravitino.iceberg.rest-catalog.security",
+            "OAUTH2");
+    GravitinoConfig config = new GravitinoConfig(configMap);
+
+    String catalogConfig = config.toCatalogConfig();
+    assertTrue(
+        catalogConfig.contains("\"gravitino.iceberg.rest-uri\"='http://127.0.0.1:9001/iceberg'"));
+    assertTrue(catalogConfig.contains("\"gravitino.iceberg.rest-catalog.security\"='OAUTH2'"));
+  }
+
   private static boolean skipCatalog(String catalogName, GravitinoConfig config) {
     for (Pattern pattern : config.getSkipCatalogPatterns()) {
       if (pattern.matcher(catalogName).matches()) {
diff --git a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
index e16afd8e6f..fc3571c8e8 100644
--- a/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
+++ b/trino-connector/trino-connector/src/test/java/org/apache/gravitino/trino/connector/catalog/iceberg/TestIcebergCatalogPropertyConverter.java
@@ -27,6 +27,7 @@ import org.apache.gravitino.Catalog;
 import org.apache.gravitino.catalog.property.PropertyConverter;
 import org.apache.gravitino.credential.Credential;
 import org.apache.gravitino.credential.JdbcCredential;
+import org.apache.gravitino.trino.connector.GravitinoConfig;
 import org.apache.gravitino.trino.connector.metadata.GravitinoCatalog;
 import org.apache.gravitino.trino.connector.metadata.TestGravitinoCatalog;
 import org.junit.jupiter.api.Assertions;
@@ -136,7 +137,7 @@ public class TestIcebergCatalogPropertyConverter {
     Catalog mockCatalog =
         TestGravitinoCatalog.mockCatalog(
             name, "lakehouse-iceberg", "test catalog", Catalog.Type.RELATIONAL, properties);
-    IcebergConnectorAdapter adapter = new IcebergConnectorAdapter();
+    IcebergConnectorAdapter adapter = new IcebergConnectorAdapter(icebergRestDisabledConfig());
 
     Map<String, String> config =
         adapter.buildInternalConnectorConfig(
@@ -176,7 +177,7 @@ public class TestIcebergCatalogPropertyConverter {
     Catalog mockCatalog =
         TestGravitinoCatalog.mockCatalog(
             name, "lakehouse-iceberg", "test catalog", Catalog.Type.RELATIONAL, properties);
-    IcebergConnectorAdapter adapter = new IcebergConnectorAdapter();
+    IcebergConnectorAdapter adapter = new IcebergConnectorAdapter(icebergRestDisabledConfig());
 
     Map<String, String> config =
         adapter.buildInternalConnectorConfig(
@@ -213,7 +214,7 @@ public class TestIcebergCatalogPropertyConverter {
     Catalog mockCatalog =
         TestGravitinoCatalog.mockCatalog(
             name, "lakehouse-iceberg", "test catalog", Catalog.Type.RELATIONAL, properties);
-    IcebergConnectorAdapter adapter = new IcebergConnectorAdapter();
+    IcebergConnectorAdapter adapter = new IcebergConnectorAdapter(icebergRestDisabledConfig());
 
     Map<String, String> config =
         adapter.buildInternalConnectorConfig(
@@ -224,4 +225,250 @@ public class TestIcebergCatalogPropertyConverter {
     Assertions.assertEquals(config.get("iceberg.jdbc-catalog.connection-user"), "root");
     Assertions.assertEquals(config.get("iceberg.jdbc-catalog.connection-password"), "ds123");
   }
+
+  @Test
+  public void testBuildConnectorPropertiesRoutesJdbcBackendThroughIcebergRest() throws Exception {
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .put("uri", "jdbc:postgresql://localhost:5432/iceberg")
+            .put("catalog-backend", "jdbc")
+            .put("jdbc-driver", "org.postgresql.Driver")
+            .put("jdbc-user", "iceberg")
+            .put("jdbc-password", "secret")
+            .put("warehouse", "s3://bucket/warehouse/")
+            .put("s3-region", "us-east-1")
+            .put("credential-providers", "s3-token")
+            .build();
+
+    Map<String, String> config =
+        buildConnectorConfig("catalog1", properties, icebergRestEnabledConfig(ImmutableMap.of()));
+
+    Assertions.assertEquals("rest", config.get("iceberg.catalog.type"));
+    Assertions.assertEquals(
+        "http://localhost:9001/iceberg", config.get("iceberg.rest-catalog.uri"));
+    Assertions.assertEquals("catalog1", config.get("iceberg.rest-catalog.prefix"));
+    // The initial GET /v1/config selects the catalog by `warehouse`, not by `prefix`.
+    Assertions.assertEquals("catalog1", config.get("iceberg.rest-catalog.warehouse"));
+    Assertions.assertEquals("true", config.get("iceberg.rest-catalog.vended-credentials-enabled"));
+
+    // The JDBC backend is how Gravitino stores the metadata; it must not reach Trino.
+    Assertions.assertNull(config.get("iceberg.jdbc-catalog.connection-url"));
+    Assertions.assertNull(config.get("iceberg.jdbc-catalog.connection-user"));
+    Assertions.assertNull(config.get("iceberg.jdbc-catalog.connection-password"));
+  }
+
+  @Test
+  public void testBuildConnectorPropertiesRoutesHiveBackendThroughIcebergRest() throws Exception {
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .put("uri", "thrift://localhost:9083")
+            .put("catalog-backend", "hive")
+            .put("warehouse", "s3://bucket/warehouse/")
+            .build();
+
+    Map<String, String> config =
+        buildConnectorConfig("catalog1", properties, icebergRestEnabledConfig(ImmutableMap.of()));
+
+    Assertions.assertEquals("rest", config.get("iceberg.catalog.type"));
+    Assertions.assertEquals("catalog1", config.get("iceberg.rest-catalog.prefix"));
+    Assertions.assertNull(config.get("hive.metastore.uri"));
+  }
+
+  @Test
+  public void testBuildConnectorPropertiesKeepsRestBackendEndpoint() throws Exception {
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .put("uri", "http://other-irc:9001/iceberg")
+            .put("catalog-backend", "rest")
+            .put("warehouse", "gt_iceberg_rest")
+            .build();
+
+    Map<String, String> config =
+        buildConnectorConfig("catalog1", properties, icebergRestEnabledConfig(ImmutableMap.of()));
+
+    Assertions.assertEquals("rest", config.get("iceberg.catalog.type"));
+    Assertions.assertEquals(
+        "http://other-irc:9001/iceberg", config.get("iceberg.rest-catalog.uri"));
+    Assertions.assertEquals("gt_iceberg_rest", config.get("iceberg.rest-catalog.warehouse"));
+    Assertions.assertNull(config.get("iceberg.rest-catalog.prefix"));
+  }
+
+  @Test
+  public void testBuildConnectorPropertiesWithIcebergRestDisabled() throws Exception {
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .put("uri", "jdbc:postgresql://localhost:5432/iceberg")
+            .put("catalog-backend", "jdbc")
+            .put("jdbc-driver", "org.postgresql.Driver")
+            .put("warehouse", "s3://bucket/warehouse/")
+            .build();
+
+    Map<String, String> config =
+        buildConnectorConfig("catalog1", properties, icebergRestDisabledConfig());
+
+    Assertions.assertEquals("jdbc", config.get("iceberg.catalog.type"));
+    Assertions.assertEquals(
+        "jdbc:postgresql://localhost:5432/iceberg",
+        config.get("iceberg.jdbc-catalog.connection-url"));
+    Assertions.assertNull(config.get("iceberg.rest-catalog.uri"));
+  }
+
+  @Test
+  public void testBuildConnectorPropertiesMissingIcebergRestUri() {
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .put("uri", "jdbc:postgresql://localhost:5432/iceberg")
+            .put("catalog-backend", "jdbc")
+            .put("jdbc-driver", "org.postgresql.Driver")
+            .build();
+    GravitinoConfig gravitinoConfig =
+        new GravitinoConfig(ImmutableMap.of("gravitino.metalake", "test"));
+
+    Assertions.assertThrows(
+        TrinoException.class, () -> buildConnectorConfig("catalog1", properties, gravitinoConfig));
+  }
+
+  @Test
+  public void testBuildConnectorPropertiesWithIcebergRestAuthentication() throws Exception {
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .put("catalog-backend", "jdbc")
+            .put("uri", "jdbc:postgresql://localhost:5432/iceberg")
+            .put("jdbc-driver", "org.postgresql.Driver")
+            .put("warehouse", "s3://bucket/warehouse/")
+            .build();
+    GravitinoConfig gravitinoConfig =
+        icebergRestEnabledConfig(
+            ImmutableMap.of(
+                "gravitino.iceberg.rest-catalog.security", "OAUTH2",
+                "gravitino.iceberg.rest-catalog.oauth2.credential", "client_id:client_secret",
+                "gravitino.iceberg.rest-catalog.uri", "http://ignored:9001/iceberg"));
+
+    Map<String, String> config = buildConnectorConfig("catalog1", properties, gravitinoConfig);
+
+    Assertions.assertEquals("OAUTH2", config.get("iceberg.rest-catalog.security"));
+    Assertions.assertEquals(
+        "client_id:client_secret", config.get("iceberg.rest-catalog.oauth2.credential"));
+    // The endpoint the connector routes to cannot be overridden by the pass-through prefix.
+    Assertions.assertEquals(
+        "http://localhost:9001/iceberg", config.get("iceberg.rest-catalog.uri"));
+  }
+
+  @Test
+  public void testBuildConnectorPropertiesForwardsSessionUser() throws Exception {
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .put("catalog-backend", "jdbc")
+            .put("uri", "jdbc:postgresql://localhost:5432/iceberg")
+            .put("jdbc-driver", "org.postgresql.Driver")
+            .build();
+
+    Map<String, String> config =
+        buildConnectorConfig(
+            "catalog1",
+            properties,
+            icebergRestEnabledConfig(
+                ImmutableMap.of("gravitino.client.session.forwardUser", "true")));
+    Assertions.assertEquals("USER", config.get("iceberg.rest-catalog.session"));
+
+    Map<String, String> explicitConfig =
+        buildConnectorConfig(
+            "catalog1",
+            properties,
+            icebergRestEnabledConfig(
+                ImmutableMap.of(
+                    "gravitino.client.session.forwardUser", "true",
+                    "gravitino.iceberg.rest-catalog.session", "NONE")));
+    Assertions.assertEquals("NONE", explicitConfig.get("iceberg.rest-catalog.session"));
+
+    Map<String, String> defaultConfig =
+        buildConnectorConfig("catalog1", properties, icebergRestEnabledConfig(ImmutableMap.of()));
+    Assertions.assertNull(defaultConfig.get("iceberg.rest-catalog.session"));
+  }
+
+  @Test
+  public void testBuildConnectorPropertiesStorageDetection() throws Exception {
+    Map<String, String> s3Config =
+        buildConnectorConfig(
+            "catalog1",
+            ImmutableMap.of(
+                "catalog-backend", "jdbc",
+                "warehouse", "s3://bucket/warehouse/",
+                "s3-region", "us-east-1",
+                "s3-endpoint", "http://minio:9000"),
+            icebergRestEnabledConfig(ImmutableMap.of()));
+    Assertions.assertEquals("true", s3Config.get("fs.native-s3.enabled"));
+    Assertions.assertEquals("us-east-1", s3Config.get("s3.region"));
+    Assertions.assertEquals("http://minio:9000", s3Config.get("s3.endpoint"));
+    Assertions.assertEquals("true", s3Config.get("fs.hadoop.enabled"));
+
+    Map<String, String> gcsConfig =
+        buildConnectorConfig(
+            "catalog1",
+            ImmutableMap.of("catalog-backend", "jdbc", "warehouse", "gs://bucket/warehouse/"),
+            icebergRestEnabledConfig(ImmutableMap.of()));
+    Assertions.assertEquals("true", gcsConfig.get("fs.native-gcs.enabled"));
+    Assertions.assertNull(gcsConfig.get("fs.native-s3.enabled"));
+
+    Map<String, String> azureConfig =
+        buildConnectorConfig(
+            "catalog1",
+            ImmutableMap.of(
+                "catalog-backend", "jdbc", "warehouse", "abfss://container@account/warehouse/"),
+            icebergRestEnabledConfig(ImmutableMap.of()));
+    Assertions.assertEquals("true", azureConfig.get("fs.native-azure.enabled"));
+
+    Map<String, String> hdfsConfig =
+        buildConnectorConfig(
+            "catalog1",
+            ImmutableMap.of("catalog-backend", "jdbc", "warehouse", "hdfs://namenode:9000/wh"),
+            icebergRestEnabledConfig(ImmutableMap.of()));
+    Assertions.assertEquals("true", hdfsConfig.get("fs.hadoop.enabled"));
+    Assertions.assertNull(hdfsConfig.get("fs.native-s3.enabled"));
+    Assertions.assertNull(hdfsConfig.get("fs.native-gcs.enabled"));
+    Assertions.assertNull(hdfsConfig.get("fs.native-azure.enabled"));
+  }
+
+  @Test
+  public void testBuildConnectorPropertiesIcebergRestKeepsCatalogBypass() throws Exception {
+    Map<String, String> properties =
+        ImmutableMap.<String, String>builder()
+            .put("catalog-backend", "jdbc")
+            .put("warehouse", "s3://bucket/warehouse/")
+            .put("trino.bypass.iceberg.table-statistics-enabled", "true")
+            .put("trino.bypass.fs.native-s3.enabled", "false")
+            .build();
+
+    Map<String, String> config =
+        buildConnectorConfig("catalog1", properties, icebergRestEnabledConfig(ImmutableMap.of()));
+
+    Assertions.assertEquals("true", config.get("iceberg.table-statistics-enabled"));
+    // A catalog can override a derived default, so a Trino release renaming it is not a blocker.
+    Assertions.assertEquals("false", config.get("fs.native-s3.enabled"));
+  }
+
+  @SuppressWarnings("unchecked")
+  private static Map<String, String> buildConnectorConfig(
+      String catalogName, Map<String, String> properties, GravitinoConfig gravitinoConfig)
+      throws Exception {
+    Catalog mockCatalog =
+        TestGravitinoCatalog.mockCatalog(
+            catalogName, "lakehouse-iceberg", "test catalog", Catalog.Type.RELATIONAL, properties);
+    return new IcebergConnectorAdapter(gravitinoConfig)
+        .buildInternalConnectorConfig(new GravitinoCatalog("test", mockCatalog), new Credential[0]);
+  }
+
+  private static GravitinoConfig icebergRestDisabledConfig() {
+    return new GravitinoConfig(
+        ImmutableMap.of("gravitino.metalake", "test", "gravitino.iceberg.rest-enabled", "false"));
+  }
+
+  private static GravitinoConfig icebergRestEnabledConfig(Map<String, String> extraConfig) {
+    return new GravitinoConfig(
+        ImmutableMap.<String, String>builder()
+            .put("gravitino.metalake", "test")
+            .put("gravitino.iceberg.rest-uri", "http://localhost:9001/iceberg")
+            .putAll(extraConfig)
+            .build());
+  }
 }


(gravitino) 07/13: [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Address review findings on the Iceberg REST routing

Posted by di...@apache.org.
This is an automated email from the ASF dual-hosted git repository.

diqiu50 pushed a commit to branch trino-irc-1.3
in repository https://gitbox.apache.org/repos/asf/gravitino.git

commit 66de2d59264e4e73ce9a93cc67cb29c805a27d05
Author: diqiu50 <di...@apache.org>
AuthorDate: Mon Aug 24 14:46:02 2026 +0800

    [Cherry-pick to branch-1.3] [#12554] improvement(trino-connector): Address review findings on the Iceberg REST routing
    
    Only inject GRAVITINO_ICEBERG_REST_PORT when a real port is supplied,
    matching the guard already in TrinoITContainers.launch. An unconditional
    injection would substitute a bare host:0 into the Trino catalog's
    gravitino.iceberg.rest-uri if a future caller passes 0, as the Copilot
    review on this PR pointed out.
    
    (cherry picked from commit 756ae3ce374c392a8dd87ec1dbb24a1c0a984040)
---
 .../integration/test/container/ContainerSuite.java | 23 ++++++++++++++--------
 1 file changed, 15 insertions(+), 8 deletions(-)

diff --git a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.java b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.java
index bc29a24e06..ad35692dbb 100644
--- a/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.java
+++ b/integration-test-common/src/test/java/org/apache/gravitino/integration/test/container/ContainerSuite.java
@@ -297,16 +297,23 @@ public class ContainerSuite implements Closeable {
           initIfNecessary();
           // Start Trino container
           String hiveContainerIp = hiveContainer.getContainerIpAddress();
+          ImmutableMap.Builder<String, String> envVars =
+              ImmutableMap.<String, String>builder()
+                  .put("HADOOP_USER_NAME", "anonymous")
+                  .put("GRAVITINO_HOST_IP", "host.docker.internal")
+                  .put("GRAVITINO_HOST_PORT", String.valueOf(gravitinoServerPort))
+                  .put("GRAVITINO_METALAKE_NAME", metalakeName);
+          if (icebergRestServerPort > 0) {
+            envVars.put("GRAVITINO_ICEBERG_REST_PORT", String.valueOf(icebergRestServerPort));
+          } else {
+            LOG.info(
+                "No Iceberg REST server port supplied; Trino falls back to the compose default. "
+                    + "Catalogs routed through the Iceberg REST server will not work in this "
+                    + "container.");
+          }
           TrinoContainer.Builder trinoBuilder =
               TrinoContainer.builder()
-                  .withEnvVars(
-                      ImmutableMap.<String, String>builder()
-                          .put("HADOOP_USER_NAME", "anonymous")
-                          .put("GRAVITINO_HOST_IP", "host.docker.internal")
-                          .put("GRAVITINO_HOST_PORT", String.valueOf(gravitinoServerPort))
-                          .put("GRAVITINO_ICEBERG_REST_PORT", String.valueOf(icebergRestServerPort))
-                          .put("GRAVITINO_METALAKE_NAME", metalakeName)
-                          .build())
+                  .withEnvVars(envVars.build())
                   .withNetwork(getNetwork())
                   .withExtraHosts(
                       ImmutableMap.<String, String>builder()