Skip to main content

risingwave_connector/connector_common/iceberg/
mod.rs

1// Copyright 2024 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15pub mod compaction;
16mod jni_catalog;
17#[cfg(any(test, feature = "test"))]
18pub mod mock_catalog;
19#[cfg(not(any(test, feature = "test")))]
20mod mock_catalog;
21mod storage_catalog;
22
23use std::collections::HashMap;
24use std::sync::{Arc, LazyLock};
25
26use ::iceberg::io::{
27    S3_ACCESS_KEY_ID, S3_ASSUME_ROLE_ARN, S3_ENDPOINT, S3_REGION, S3_SECRET_ACCESS_KEY,
28};
29use ::iceberg::table::Table;
30use ::iceberg::{Catalog, CatalogBuilder, TableIdent};
31use anyhow::{Context, anyhow};
32use iceberg::io::object_cache::ObjectCache;
33use iceberg::io::{
34    ADLS_ACCOUNT_KEY, ADLS_ACCOUNT_NAME, ADLS_AUTHORITY_HOST, ADLS_CLIENT_ID, ADLS_CLIENT_SECRET,
35    ADLS_TENANT_ID, AZBLOB_ACCOUNT_KEY, AZBLOB_ACCOUNT_NAME, AZBLOB_ENDPOINT, GCS_CREDENTIALS_JSON,
36    GCS_DISABLE_CONFIG_LOAD, S3_DISABLE_CONFIG_LOAD, S3_PATH_STYLE_ACCESS,
37};
38use iceberg_catalog_glue::{AWS_ACCESS_KEY_ID, AWS_REGION_NAME, AWS_SECRET_ACCESS_KEY};
39use iceberg_storage_opendal::OpenDalResolvingStorageFactory;
40use moka::future::Cache as MokaCache;
41use phf::{Set, phf_set};
42use risingwave_common::bail;
43use risingwave_common::error::IcebergError;
44use risingwave_common::util::deployment::Deployment;
45use risingwave_common::util::env_var::env_var_is_true;
46use serde::Deserialize;
47use serde_with::serde_as;
48use url::Url;
49use uuid::Uuid;
50use with_options::WithOptions;
51
52use crate::connector_common::common::DISABLE_DEFAULT_CREDENTIAL;
53use crate::connector_common::iceberg::storage_catalog::StorageCatalogConfig;
54use crate::deserialize_optional_bool_from_string;
55use crate::enforce_secret::EnforceSecret;
56use crate::error::ConnectorResult;
57
58#[serde_as]
59#[derive(Debug, Clone, PartialEq, Eq, Deserialize, WithOptions)]
60pub struct IcebergCommon {
61    // Catalog type supported by iceberg, such as "storage", "rest".
62    // If not set, we use "storage" as default.
63    #[serde(rename = "catalog.type")]
64    pub catalog_type: Option<String>,
65    #[serde(rename = "s3.region")]
66    pub s3_region: Option<String>,
67    #[serde(rename = "s3.endpoint")]
68    pub s3_endpoint: Option<String>,
69    #[serde(rename = "s3.access.key")]
70    pub s3_access_key: Option<String>,
71    #[serde(rename = "s3.secret.key")]
72    pub s3_secret_key: Option<String>,
73    #[serde(rename = "s3.iam_role_arn")]
74    pub s3_iam_role_arn: Option<String>,
75
76    #[serde(rename = "glue.access.key")]
77    pub glue_access_key: Option<String>,
78    #[serde(rename = "glue.secret.key")]
79    pub glue_secret_key: Option<String>,
80    #[serde(rename = "glue.iam_role_arn")]
81    pub glue_iam_role_arn: Option<String>,
82    #[serde(rename = "glue.region")]
83    pub glue_region: Option<String>,
84    #[serde(rename = "glue.endpoint")]
85    pub glue_endpoint: Option<String>,
86    /// AWS Client id, can be omitted for storage catalog or when
87    /// caller's AWS account ID matches glue id
88    #[serde(rename = "glue.id")]
89    pub glue_id: Option<String>,
90
91    #[serde(rename = "gcs.credential")]
92    pub gcs_credential: Option<String>,
93
94    #[serde(rename = "azblob.account_name")]
95    pub azblob_account_name: Option<String>,
96    #[serde(rename = "azblob.account_key")]
97    pub azblob_account_key: Option<String>,
98    #[serde(rename = "azblob.endpoint_url")]
99    pub azblob_endpoint_url: Option<String>,
100
101    #[serde(rename = "adlsgen2.account_name")]
102    pub adlsgen2_account_name: Option<String>,
103    #[serde(rename = "adlsgen2.account_key")]
104    pub adlsgen2_account_key: Option<String>,
105    #[serde(rename = "adlsgen2.endpoint")]
106    pub adlsgen2_endpoint: Option<String>,
107    #[serde(rename = "adlsgen2.tenant_id")]
108    pub adlsgen2_tenant_id: Option<String>,
109    #[serde(rename = "adlsgen2.client_id")]
110    pub adlsgen2_client_id: Option<String>,
111    #[serde(rename = "adlsgen2.client_secret")]
112    pub adlsgen2_client_secret: Option<String>,
113    #[serde(rename = "adlsgen2.authority_host")]
114    pub adlsgen2_authority_host: Option<String>,
115
116    /// Path of iceberg warehouse.
117    #[serde(rename = "warehouse.path")]
118    pub warehouse_path: Option<String>,
119    /// Catalog name, default value is risingwave.
120    #[serde(rename = "catalog.name")]
121    pub catalog_name: Option<String>,
122    /// URI of iceberg catalog, only applicable in rest catalog.
123    #[serde(rename = "catalog.uri")]
124    pub catalog_uri: Option<String>,
125    /// Credential for accessing iceberg catalog, only applicable in rest catalog.
126    /// A credential to exchange for a token in the `OAuth2` client credentials flow.
127    #[serde(rename = "catalog.credential")]
128    pub catalog_credential: Option<String>,
129    /// token for accessing iceberg catalog, only applicable in rest catalog.
130    /// A Bearer token which will be used for interaction with the server.
131    #[serde(rename = "catalog.token")]
132    pub catalog_token: Option<String>,
133    /// `oauth2_server_uri` for accessing iceberg catalog, only applicable in rest catalog.
134    /// Token endpoint URI to fetch token from if the Rest Catalog is not the authorization server.
135    #[serde(rename = "catalog.oauth2_server_uri")]
136    pub catalog_oauth2_server_uri: Option<String>,
137    /// scope for accessing iceberg catalog, only applicable in rest catalog.
138    /// Additional scope for `OAuth2`.
139    #[serde(rename = "catalog.scope")]
140    pub catalog_scope: Option<String>,
141
142    /// The signing region to use when signing requests to the REST catalog.
143    #[serde(rename = "catalog.rest.signing_region")]
144    pub rest_signing_region: Option<String>,
145
146    /// The signing name to use when signing requests to the REST catalog.
147    #[serde(rename = "catalog.rest.signing_name")]
148    pub rest_signing_name: Option<String>,
149
150    /// Whether to use `SigV4` for signing requests to the REST catalog.
151    #[serde(
152        rename = "catalog.rest.sigv4_enabled",
153        default,
154        deserialize_with = "deserialize_optional_bool_from_string"
155    )]
156    pub rest_sigv4_enabled: Option<bool>,
157
158    #[serde(
159        rename = "s3.path.style.access",
160        default,
161        deserialize_with = "deserialize_optional_bool_from_string"
162    )]
163    pub s3_path_style_access: Option<bool>,
164    /// Enable config load. This parameter set to true will load warehouse credentials from the environment. Only allowed to be used in a self-hosted environment.
165    #[serde(default, deserialize_with = "deserialize_optional_bool_from_string")]
166    pub enable_config_load: Option<bool>,
167
168    /// This is only used by iceberg engine to enable the hosted catalog.
169    #[serde(
170        rename = "hosted_catalog",
171        default,
172        deserialize_with = "deserialize_optional_bool_from_string"
173    )]
174    pub hosted_catalog: Option<bool>,
175
176    /// The HTTP header to be used in catalog requests.
177    /// Example:
178    /// `catalog.header = "key1=value1;key2=value2;key3=value3"`
179    /// For Google Cloud Lakehouse Iceberg REST catalogs, set
180    /// `catalog.header = "x-goog-user-project=PROJECT_ID"` to specify the billing project.
181    /// Explain the format of the header:
182    /// - Each header is a key-value pair, separated by an '='.
183    /// - Multiple headers can be specified, separated by a ';'.
184    #[serde(rename = "catalog.header")]
185    pub catalog_header: Option<String>,
186
187    /// Enable vended credentials for Iceberg REST catalog.
188    /// For Google Cloud Lakehouse Iceberg REST catalogs, this sends
189    /// `X-Iceberg-Access-Delegation: vended-credentials`.
190    #[serde(default, deserialize_with = "deserialize_optional_bool_from_string")]
191    pub vended_credentials: Option<bool>,
192
193    /// Security type for REST catalog authentication.
194    /// Supported values: `none`, `oauth2`, `google`.
195    /// When set to `google`, native REST catalogs authenticate using
196    /// `gcs.credential` or Google Application Default Credentials (ADC).
197    /// JNI REST catalogs use Java's `GoogleAuthManager` with ADC;
198    /// `gcs.credential` only configures Rust `FileIO` storage credentials.
199    /// Vended credentials use the native Rust REST catalog.
200    #[serde(rename = "catalog.security")]
201    pub catalog_security: Option<String>,
202
203    /// OAuth-based scopes for Google authentication.
204    /// Comma-separated list of OAuth-based scopes to request.
205    /// Only applicable when `catalog.security` is set to `google`.
206    /// Default: <https://www.googleapis.com/auth/cloud-platform>
207    #[serde(rename = "gcp.auth.scopes")]
208    pub gcp_auth_scopes: Option<String>,
209
210    /// Custom `FileIO` implementation class for the Iceberg catalog.
211    /// Allows specifying a custom `FileIO` implementation instead of the default.
212    /// Examples:
213    /// - `org.apache.iceberg.aws.s3.S3FileIO` for Amazon S3 (default)
214    /// - `org.apache.iceberg.gcp.gcs.GCSFileIO` for Google Cloud Storage
215    /// - `org.apache.iceberg.azure.adlsv2.ADLSFileIO` for Azure Data Lake Storage Gen2
216    /// Applies only to JNI catalogs. Native REST catalogs route storage by URI
217    /// and support GCS vended credentials without a Java `FileIO` class.
218    #[serde(rename = "catalog.io_impl")]
219    pub catalog_io_impl: Option<String>,
220}
221
222// Matches iceberg::io::object_cache default size (32MB).
223// TODO: change it after object cache get refactored.
224const DEFAULT_OBJECT_CACHE_SIZE_BYTES: u64 = 32 * 1024 * 1024;
225const SHARED_OBJECT_CACHE_BUDGET_BYTES: u64 = 512 * 1024 * 1024;
226const SHARED_OBJECT_CACHE_MAX_TABLES: u64 =
227    SHARED_OBJECT_CACHE_BUDGET_BYTES / DEFAULT_OBJECT_CACHE_SIZE_BYTES;
228
229/// Default Microsoft Entra (AAD) authority host for public Azure. Sovereign-cloud
230/// users override via `adlsgen2.authority_host`.
231const ADLS_DEFAULT_AUTHORITY_HOST: &str = "https://login.microsoftonline.com";
232
233impl EnforceSecret for IcebergCommon {
234    const ENFORCE_SECRET_PROPERTIES: Set<&'static str> = phf_set! {
235        "s3.access.key",
236        "s3.secret.key",
237        "gcs.credential",
238        "catalog.credential",
239        "catalog.token",
240        "catalog.oauth2_server_uri",
241        "adlsgen2.account_key",
242        "adlsgen2.client_secret",
243        "glue.access.key",
244        "glue.secret.key",
245    };
246}
247
248#[serde_as]
249#[derive(Debug, Clone, PartialEq, Eq, Deserialize, WithOptions)]
250#[serde(deny_unknown_fields)]
251pub struct IcebergTableIdentifier {
252    #[serde(rename = "database.name")]
253    pub database_name: Option<String>,
254    /// Table name or namespace-qualified table name. Dots are treated as
255    /// Iceberg namespace separators.
256    #[serde(rename = "table.name")]
257    pub table_name: String,
258}
259
260impl IcebergTableIdentifier {
261    pub fn database_name(&self) -> Option<&str> {
262        self.database_name.as_deref()
263    }
264
265    pub fn table_name(&self) -> &str {
266        &self.table_name
267    }
268
269    fn identifier_parts(&self) -> ConnectorResult<Vec<&str>> {
270        let mut parts = Vec::new();
271        if let Some(database_name) = &self.database_name {
272            parts.extend(database_name.split('.'));
273        }
274        parts.extend(self.table_name.split('.'));
275
276        if parts.iter().any(|part| part.is_empty()) {
277            bail!(
278                "Invalid iceberg table identifier '{}': identifier parts must not be empty",
279                self.full_identifier()
280            );
281        }
282
283        Ok(parts)
284    }
285
286    fn full_identifier(&self) -> String {
287        match &self.database_name {
288            Some(database_name) => format!("{}.{}", database_name, self.table_name),
289            None => self.table_name.clone(),
290        }
291    }
292
293    pub fn to_table_ident(&self) -> ConnectorResult<TableIdent> {
294        let ret = TableIdent::from_strs(self.identifier_parts()?);
295
296        Ok(ret.context("Failed to create table identifier")?)
297    }
298
299    pub fn validate(&self) -> ConnectorResult<()> {
300        self.identifier_parts().map(|_| ())
301    }
302}
303
304#[derive(Debug, Clone, Copy, PartialEq, Eq)]
305pub enum IcebergCatalogRuntime {
306    NativeRust,
307    JavaJni,
308}
309
310#[derive(Debug, Clone, Copy, PartialEq, Eq)]
311pub enum IcebergCatalogKind {
312    Storage,
313    Rest(IcebergCatalogRuntime),
314    Glue(IcebergCatalogRuntime),
315    Hive,
316    Jdbc,
317    Snowflake,
318    Mock,
319}
320
321impl IcebergCatalogKind {
322    fn resolve(common: &IcebergCommon) -> ConnectorResult<Self> {
323        let catalog_type = common.catalog_type();
324        let kind = match catalog_type {
325            "storage" => Self::Storage,
326            "rest" if common.vended_credentials() => Self::Rest(IcebergCatalogRuntime::NativeRust),
327            "rest" => Self::Rest(IcebergCatalogRuntime::JavaJni),
328            "rest_rust" => Self::Rest(IcebergCatalogRuntime::NativeRust),
329            "glue" => Self::Glue(IcebergCatalogRuntime::JavaJni),
330            "glue_rust" => Self::Glue(IcebergCatalogRuntime::NativeRust),
331            "hive" => Self::Hive,
332            "jdbc" => Self::Jdbc,
333            "snowflake" => Self::Snowflake,
334            #[cfg(any(test, madsim))]
335            "mock_v3" => Self::Mock,
336            "mock" => Self::Mock,
337            _ => {
338                bail!(
339                    "Unsupported catalog type: {}, only support `storage`, `rest`, `hive`, `jdbc`, `glue`, `snowflake`",
340                    catalog_type
341                )
342            }
343        };
344        Ok(kind)
345    }
346
347    pub fn is_rest(self) -> bool {
348        matches!(self, Self::Rest(_))
349    }
350
351    fn jni_impl(self) -> Option<JniCatalogImpl> {
352        match self {
353            Self::Rest(IcebergCatalogRuntime::JavaJni) => Some(JniCatalogImpl::Rest),
354            Self::Glue(IcebergCatalogRuntime::JavaJni) => Some(JniCatalogImpl::Glue),
355            Self::Hive => Some(JniCatalogImpl::Hive),
356            Self::Jdbc => Some(JniCatalogImpl::Jdbc),
357            Self::Snowflake => Some(JniCatalogImpl::Snowflake),
358            _ => None,
359        }
360    }
361}
362
363#[derive(Debug, Clone, Copy, PartialEq, Eq)]
364enum JniCatalogImpl {
365    Hive,
366    Jdbc,
367    Snowflake,
368    Rest,
369    Glue,
370}
371
372impl JniCatalogImpl {
373    fn catalog_type(self) -> &'static str {
374        match self {
375            Self::Hive => "hive",
376            Self::Jdbc => "jdbc",
377            Self::Snowflake => "snowflake",
378            Self::Rest => "rest",
379            Self::Glue => "glue",
380        }
381    }
382
383    fn class_name(self) -> &'static str {
384        match self {
385            Self::Hive => "org.apache.iceberg.hive.HiveCatalog",
386            Self::Jdbc => "org.apache.iceberg.jdbc.JdbcCatalog",
387            Self::Snowflake => "org.apache.iceberg.snowflake.SnowflakeCatalog",
388            Self::Rest => "org.apache.iceberg.rest.RESTCatalog",
389            Self::Glue => "org.apache.iceberg.aws.glue.GlueCatalog",
390        }
391    }
392}
393
394enum CatalogBuildPlan {
395    Storage(StorageCatalogConfig),
396    NativeRest(HashMap<String, String>),
397    NativeGlue(HashMap<String, String>),
398    Jni {
399        file_io_props: HashMap<String, String>,
400        catalog_name: String,
401        catalog_impl: JniCatalogImpl,
402        java_catalog_props: HashMap<String, String>,
403    },
404    Mock,
405}
406
407pub struct ResolvedIcebergCatalogConfig<'a> {
408    common: &'a IcebergCommon,
409    kind: IcebergCatalogKind,
410    java_catalog_props: HashMap<String, String>,
411}
412
413impl<'a> ResolvedIcebergCatalogConfig<'a> {
414    pub fn kind(&self) -> IcebergCatalogKind {
415        self.kind
416    }
417
418    fn build_plan(&self) -> ConnectorResult<CatalogBuildPlan> {
419        match self.kind {
420            IcebergCatalogKind::Storage => self.common.build_storage_catalog_config(),
421            IcebergCatalogKind::Rest(IcebergCatalogRuntime::NativeRust) => {
422                self.common.build_native_rest_catalog_props()
423            }
424            IcebergCatalogKind::Glue(IcebergCatalogRuntime::NativeRust) => {
425                self.common.build_native_glue_catalog_props()
426            }
427            IcebergCatalogKind::Mock => Ok(CatalogBuildPlan::Mock),
428            kind => {
429                let catalog_impl = kind.jni_impl().expect("java catalog kind has JNI impl");
430                let (file_io_props, java_catalog_props) = self
431                    .common
432                    .build_jni_catalog_configs(catalog_impl, &self.java_catalog_props)?;
433                Ok(CatalogBuildPlan::Jni {
434                    file_io_props,
435                    catalog_name: self.common.catalog_name(),
436                    catalog_impl,
437                    java_catalog_props,
438                })
439            }
440        }
441    }
442
443    pub async fn create_catalog(&self) -> ConnectorResult<Arc<dyn Catalog>> {
444        match self.build_plan()? {
445            CatalogBuildPlan::Storage(config) => {
446                let catalog = storage_catalog::StorageCatalog::new(config)?;
447                Ok(Arc::new(catalog))
448            }
449            CatalogBuildPlan::NativeRest(iceberg_configs) => {
450                let catalog = iceberg_catalog_rest::RestCatalogBuilder::default()
451                    .with_storage_factory(Arc::new(OpenDalResolvingStorageFactory::new()))
452                    .load("rest", iceberg_configs)
453                    .await
454                    .map_err(|e| anyhow!(IcebergError::from(e)))?;
455                Ok(Arc::new(catalog))
456            }
457            CatalogBuildPlan::NativeGlue(iceberg_configs) => {
458                let catalog = iceberg_catalog_glue::GlueCatalogBuilder::default()
459                    .load("glue", iceberg_configs)
460                    .await
461                    .map_err(|e| anyhow!(IcebergError::from(e)))?;
462                Ok(Arc::new(catalog))
463            }
464            CatalogBuildPlan::Jni {
465                file_io_props,
466                catalog_name,
467                catalog_impl,
468                java_catalog_props,
469            } => {
470                jni_catalog::JniCatalog::build_catalog(
471                    file_io_props,
472                    catalog_name,
473                    catalog_impl.class_name(),
474                    java_catalog_props,
475                )
476                .await
477            }
478            CatalogBuildPlan::Mock => Ok(Arc::new(mock_catalog::MockCatalog {})),
479        }
480    }
481
482    pub async fn load_table(&self, table: &IcebergTableIdentifier) -> ConnectorResult<Table> {
483        let catalog = self
484            .create_catalog()
485            .await
486            .context("Unable to load iceberg catalog")?;
487
488        let table_id = table
489            .to_table_ident()
490            .context("Unable to parse table name")?;
491
492        let table = catalog.load_table(&table_id).await?;
493        Ok(rebuild_table_with_shared_cache(table).await)
494    }
495}
496
497pub fn iceberg_java_catalog_props_from_options<'a>(
498    options: impl Iterator<Item = (&'a str, &'a str)>,
499) -> HashMap<String, String> {
500    options
501        .filter(|(k, _v)| {
502            k.starts_with("catalog.")
503                && k != &"catalog.uri"
504                && k != &"catalog.type"
505                && k != &"catalog.name"
506                && k != &"catalog.header"
507        })
508        .map(|(k, v)| (k[8..].to_owned(), v.to_owned()))
509        .collect()
510}
511
512impl IcebergCommon {
513    pub fn catalog_type(&self) -> &str {
514        self.catalog_type.as_deref().unwrap_or("storage")
515    }
516
517    pub fn vended_credentials(&self) -> bool {
518        self.vended_credentials.unwrap_or(false)
519    }
520
521    pub fn resolve_catalog_kind(&self) -> ConnectorResult<IcebergCatalogKind> {
522        IcebergCatalogKind::resolve(self)
523    }
524
525    pub fn is_rest_catalog(&self) -> ConnectorResult<bool> {
526        Ok(self.resolve_catalog_kind()?.is_rest())
527    }
528
529    pub fn resolve_catalog_config(
530        &self,
531        java_catalog_props: HashMap<String, String>,
532    ) -> ConnectorResult<ResolvedIcebergCatalogConfig<'_>> {
533        Ok(ResolvedIcebergCatalogConfig {
534            common: self,
535            kind: self.resolve_catalog_kind()?,
536            java_catalog_props,
537        })
538    }
539
540    fn glue_access_key(&self) -> Option<&str> {
541        self.glue_access_key
542            .as_deref()
543            .or(self.s3_access_key.as_deref())
544    }
545
546    fn glue_secret_key(&self) -> Option<&str> {
547        self.glue_secret_key
548            .as_deref()
549            .or(self.s3_secret_key.as_deref())
550    }
551
552    fn glue_region(&self) -> Option<&str> {
553        self.glue_region.as_deref().or(self.s3_region.as_deref())
554    }
555
556    fn glue_endpoint(&self) -> Option<&str> {
557        self.glue_endpoint
558            .as_deref()
559            .or_else(|| match self.resolve_catalog_kind() {
560                Ok(IcebergCatalogKind::Glue(IcebergCatalogRuntime::JavaJni)) => {
561                    self.catalog_uri.as_deref()
562                }
563                _ => None,
564            })
565    }
566
567    pub fn catalog_name(&self) -> String {
568        self.catalog_name
569            .as_ref()
570            .cloned()
571            .unwrap_or_else(|| "risingwave".to_owned())
572    }
573
574    pub fn headers(&self) -> ConnectorResult<HashMap<String, String>> {
575        let mut headers = HashMap::new();
576        let user_agent = match Deployment::current() {
577            Deployment::Ci => "RisingWave(CI)".to_owned(),
578            Deployment::Cloud => "RisingWave(Cloud)".to_owned(),
579            Deployment::Other => "RisingWave(OSS)".to_owned(),
580        };
581        if self.vended_credentials() {
582            headers.insert(
583                "X-Iceberg-Access-Delegation".to_owned(),
584                "vended-credentials".to_owned(),
585            );
586        }
587        headers.insert("User-Agent".to_owned(), user_agent);
588        if let Some(header) = &self.catalog_header {
589            for pair in header.split(';') {
590                let mut parts = pair.split('=');
591                if let (Some(key), Some(value)) = (parts.next(), parts.next()) {
592                    headers.insert(key.to_owned(), value.to_owned());
593                } else {
594                    bail!("Invalid header format: {}", pair);
595                }
596            }
597        }
598        Ok(headers)
599    }
600
601    pub fn enable_config_load(&self) -> bool {
602        // If the env var is set to true, we disable the default config load. (Cloud environment)
603        if env_var_is_true(DISABLE_DEFAULT_CREDENTIAL) {
604            if matches!(self.enable_config_load, Some(true)) {
605                tracing::warn!(
606                    "`enable_config_load` can't be enabled in SaaS environment, the behavior might be unexpected"
607                );
608            }
609            return false;
610        }
611        self.enable_config_load.unwrap_or(false)
612    }
613
614    fn effective_s3_path_style_access(&self) -> bool {
615        // RisingWave historically inherited OpenDAL's path-style default. Iceberg now
616        // defaults to virtual-host style, so preserve existing connector behavior unless
617        // the user explicitly opts into virtual-host style with `false`.
618        self.s3_path_style_access.unwrap_or(true)
619    }
620
621    fn build_storage_catalog_config(&self) -> ConnectorResult<CatalogBuildPlan> {
622        let warehouse = self
623            .warehouse_path
624            .clone()
625            .ok_or_else(|| anyhow!("`warehouse.path` must be set in storage catalog"))?;
626        let url = Url::parse(warehouse.as_ref())
627            .map_err(|_| anyhow!("Invalid warehouse path: {}", warehouse))?;
628
629        let config = match url.scheme() {
630            "s3" | "s3a" => StorageCatalogConfig::S3(
631                storage_catalog::StorageCatalogS3Config::builder()
632                    .warehouse(warehouse)
633                    .access_key(self.s3_access_key.clone())
634                    .secret_key(self.s3_secret_key.clone())
635                    .iam_role_arn(self.s3_iam_role_arn.clone())
636                    .region(self.s3_region.clone())
637                    .endpoint(self.s3_endpoint.clone())
638                    .path_style_access(Some(self.effective_s3_path_style_access()))
639                    .enable_config_load(Some(self.enable_config_load()))
640                    .build(),
641            ),
642            "gs" | "gcs" => StorageCatalogConfig::Gcs(
643                storage_catalog::StorageCatalogGcsConfig::builder()
644                    .warehouse(warehouse)
645                    .credential(self.gcs_credential.clone())
646                    .enable_config_load(Some(self.enable_config_load()))
647                    .build(),
648            ),
649            "azblob" => StorageCatalogConfig::Azblob(
650                storage_catalog::StorageCatalogAzblobConfig::builder()
651                    .warehouse(warehouse)
652                    .account_name(self.azblob_account_name.clone())
653                    .account_key(self.azblob_account_key.clone())
654                    .endpoint(self.azblob_endpoint_url.clone())
655                    .build(),
656            ),
657            scheme => bail!("Unsupported warehouse scheme: {}", scheme),
658        };
659
660        Ok(CatalogBuildPlan::Storage(config))
661    }
662
663    fn validate_native_rest_catalog_auth(
664        &self,
665        disable_default_credential: bool,
666    ) -> ConnectorResult<()> {
667        if disable_default_credential
668            && self
669                .catalog_security
670                .as_deref()
671                .is_some_and(|security| security.eq_ignore_ascii_case("google"))
672            && self.gcs_credential.is_none()
673        {
674            // Google token refresh uses ADC without a GCS credential, even when
675            // a catalog token or OAuth credential was explicitly provided.
676            bail!(
677                "`catalog.security=google` requires `gcs.credential` when `DISABLE_DEFAULT_CREDENTIAL=true`"
678            );
679        }
680        Ok(())
681    }
682
683    fn build_native_rest_catalog_props(&self) -> ConnectorResult<CatalogBuildPlan> {
684        self.validate_native_rest_catalog_auth(env_var_is_true(DISABLE_DEFAULT_CREDENTIAL))?;
685
686        let mut iceberg_configs = HashMap::new();
687        iceberg_configs.extend(self.adls_file_io_props()?);
688
689        if self
690            .catalog_security
691            .as_deref()
692            .is_some_and(|security| security.eq_ignore_ascii_case("google"))
693        {
694            iceberg_configs.insert("rest.auth.type".to_owned(), "google".to_owned());
695        }
696        if let Some(scopes) = &self.gcp_auth_scopes {
697            iceberg_configs.insert("gcp.auth.scopes".to_owned(), scopes.clone());
698        }
699
700        // check gcs credential or s3 access key and secret key
701        if let Some(gcs_credential) = &self.gcs_credential {
702            iceberg_configs.insert(GCS_CREDENTIALS_JSON.to_owned(), gcs_credential.clone());
703        } else {
704            if let Some(region) = &self.s3_region {
705                iceberg_configs.insert(S3_REGION.to_owned(), region.clone());
706            }
707            if let Some(endpoint) = &self.s3_endpoint {
708                iceberg_configs.insert(S3_ENDPOINT.to_owned(), endpoint.clone());
709            }
710            if let Some(access_key) = &self.s3_access_key {
711                iceberg_configs.insert(S3_ACCESS_KEY_ID.to_owned(), access_key.clone());
712            }
713            if let Some(secret_key) = &self.s3_secret_key {
714                iceberg_configs.insert(S3_SECRET_ACCESS_KEY.to_owned(), secret_key.clone());
715            }
716            if let Some(path_style_access) = &self.s3_path_style_access {
717                iceberg_configs.insert(
718                    S3_PATH_STYLE_ACCESS.to_owned(),
719                    path_style_access.to_string(),
720                );
721            }
722        };
723
724        if let Some(credential) = &self.catalog_credential {
725            iceberg_configs.insert("credential".to_owned(), credential.clone());
726        }
727        if let Some(token) = &self.catalog_token {
728            iceberg_configs.insert("token".to_owned(), token.clone());
729        }
730        if let Some(oauth2_server_uri) = &self.catalog_oauth2_server_uri {
731            iceberg_configs.insert("oauth2-server-uri".to_owned(), oauth2_server_uri.clone());
732        }
733        if let Some(scope) = &self.catalog_scope {
734            iceberg_configs.insert("scope".to_owned(), scope.clone());
735        }
736
737        let headers = self.headers()?;
738        for (header_name, header_value) in headers {
739            iceberg_configs.insert(format!("header.{}", header_name), header_value);
740        }
741
742        iceberg_configs.insert(
743            iceberg_catalog_rest::REST_CATALOG_PROP_URI.to_owned(),
744            self.catalog_uri
745                .clone()
746                .with_context(|| "`catalog.uri` must be set in rest catalog".to_owned())?,
747        );
748        if let Some(warehouse_path) = &self.warehouse_path {
749            iceberg_configs.insert(
750                iceberg_catalog_rest::REST_CATALOG_PROP_WAREHOUSE.to_owned(),
751                warehouse_path.clone(),
752            );
753        }
754
755        Ok(CatalogBuildPlan::NativeRest(iceberg_configs))
756    }
757
758    fn adls_file_io_props(&self) -> ConnectorResult<HashMap<String, String>> {
759        let mut props = HashMap::new();
760        if let Some(endpoint) = &self.adlsgen2_endpoint {
761            props.insert(iceberg::io::ADLS_ENDPOINT.to_owned(), endpoint.clone());
762        }
763        let nonempty =
764            |value: &Option<String>| value.as_ref().filter(|s| !s.trim().is_empty()).cloned();
765        let tenant = nonempty(&self.adlsgen2_tenant_id);
766        let client = nonempty(&self.adlsgen2_client_id);
767        let secret = nonempty(&self.adlsgen2_client_secret);
768        let authority = nonempty(&self.adlsgen2_authority_host);
769        let account = nonempty(&self.adlsgen2_account_name);
770        let key = nonempty(&self.adlsgen2_account_key);
771        let any_sp =
772            tenant.is_some() || client.is_some() || secret.is_some() || authority.is_some();
773        if key.is_some() && any_sp {
774            bail!(
775                "adlsgen2: cannot configure both shared-key auth and service-principal auth simultaneously. Specify exactly one auth mode."
776            );
777        }
778        if any_sp && !(tenant.is_some() && client.is_some() && secret.is_some()) {
779            bail!(
780                "adlsgen2: service-principal auth requires all three of adlsgen2.tenant_id, adlsgen2.client_id, and adlsgen2.client_secret to be set"
781            );
782        }
783        if let Some(host) = &authority {
784            // The OAuth client sends its secret to this host. Only allow a bare HTTPS origin.
785            let parsed = Url::parse(host)
786                .map_err(|_| anyhow!("adlsgen2.authority_host does not parse as a URL"))?;
787            if parsed.scheme() != "https" {
788                bail!("adlsgen2.authority_host must use the https scheme");
789            }
790            if !parsed.username().is_empty() || parsed.password().is_some() {
791                bail!("adlsgen2.authority_host must not contain userinfo");
792            }
793            if parsed.query().is_some() || parsed.fragment().is_some() {
794                bail!("adlsgen2.authority_host must not contain a query or fragment");
795            }
796            if !matches!(parsed.path(), "" | "/") {
797                bail!("adlsgen2.authority_host must not contain a path component");
798            }
799        }
800        if let (Some(account), Some(key)) = (account, key) {
801            props.insert(ADLS_ACCOUNT_NAME.to_owned(), account);
802            props.insert(ADLS_ACCOUNT_KEY.to_owned(), key);
803        }
804        if let (Some(tenant), Some(client), Some(secret)) = (tenant, client, secret) {
805            props.insert(ADLS_TENANT_ID.to_owned(), tenant);
806            props.insert(ADLS_CLIENT_ID.to_owned(), client);
807            props.insert(ADLS_CLIENT_SECRET.to_owned(), secret);
808            props.insert(
809                ADLS_AUTHORITY_HOST.to_owned(),
810                authority
811                    .as_deref()
812                    .unwrap_or(ADLS_DEFAULT_AUTHORITY_HOST)
813                    .trim_end_matches('/')
814                    .to_owned(),
815            );
816        }
817        Ok(props)
818    }
819
820    fn build_native_glue_catalog_props(&self) -> ConnectorResult<CatalogBuildPlan> {
821        let mut iceberg_configs = HashMap::new();
822        // glue
823        if let Some(region) = self.glue_region() {
824            iceberg_configs.insert(AWS_REGION_NAME.to_owned(), region.to_owned());
825        }
826        if let Some(access_key) = self.glue_access_key() {
827            iceberg_configs.insert(AWS_ACCESS_KEY_ID.to_owned(), access_key.to_owned());
828        }
829        if let Some(secret_key) = self.glue_secret_key() {
830            iceberg_configs.insert(AWS_SECRET_ACCESS_KEY.to_owned(), secret_key.to_owned());
831        }
832        // s3
833        if let Some(region) = &self.s3_region {
834            iceberg_configs.insert(S3_REGION.to_owned(), region.clone());
835        }
836        if let Some(endpoint) = &self.s3_endpoint {
837            iceberg_configs.insert(S3_ENDPOINT.to_owned(), endpoint.clone());
838        }
839        if let Some(access_key) = &self.s3_access_key {
840            iceberg_configs.insert(S3_ACCESS_KEY_ID.to_owned(), access_key.clone());
841        }
842        if let Some(secret_key) = &self.s3_secret_key {
843            iceberg_configs.insert(S3_SECRET_ACCESS_KEY.to_owned(), secret_key.clone());
844        }
845        if let Some(role_arn) = &self.s3_iam_role_arn {
846            iceberg_configs.insert(S3_ASSUME_ROLE_ARN.to_owned(), role_arn.clone());
847        }
848        iceberg_configs.insert(
849            S3_PATH_STYLE_ACCESS.to_owned(),
850            self.effective_s3_path_style_access().to_string(),
851        );
852        iceberg_configs.insert(
853            iceberg_catalog_glue::GLUE_CATALOG_PROP_WAREHOUSE.to_owned(),
854            self.warehouse_path
855                .clone()
856                .ok_or_else(|| anyhow!("`warehouse.path` must be set in glue catalog"))?,
857        );
858        if let Some(uri) = self.catalog_uri.as_deref() {
859            iceberg_configs.insert(
860                iceberg_catalog_glue::GLUE_CATALOG_PROP_URI.to_owned(),
861                uri.to_owned(),
862            );
863        }
864
865        Ok(CatalogBuildPlan::NativeGlue(iceberg_configs))
866    }
867
868    /// For both V1 and V2.
869    fn build_jni_catalog_configs(
870        &self,
871        catalog_impl: JniCatalogImpl,
872        java_catalog_props: &HashMap<String, String>,
873    ) -> ConnectorResult<(HashMap<String, String>, HashMap<String, String>)> {
874        let mut iceberg_configs = HashMap::new();
875        let enable_config_load = self.enable_config_load();
876        let file_io_props = {
877            let catalog_type = catalog_impl.catalog_type();
878
879            // Non-S3/Glue object-store backends only work with a REST catalog. This
880            // function is only invoked for catalog_type in {hive, snowflake, jdbc, rest,
881            // glue}, so the only accepted value here is "rest".
882            let require_rest = |backend: &str| -> ConnectorResult<()> {
883                if catalog_impl != JniCatalogImpl::Rest {
884                    bail!("{} unsupported in {} catalog", backend, catalog_type);
885                }
886                Ok(())
887            };
888
889            if let Some(region) = &self.s3_region {
890                // iceberg-rust
891                iceberg_configs.insert(S3_REGION.to_owned(), region.clone());
892            }
893
894            if let Some(endpoint) = &self.s3_endpoint {
895                // iceberg-rust
896                iceberg_configs.insert(S3_ENDPOINT.to_owned(), endpoint.clone());
897            }
898
899            // iceberg-rust
900            if let Some(access_key) = &self.s3_access_key {
901                iceberg_configs.insert(S3_ACCESS_KEY_ID.to_owned(), access_key.clone());
902            }
903            if let Some(secret_key) = &self.s3_secret_key {
904                iceberg_configs.insert(S3_SECRET_ACCESS_KEY.to_owned(), secret_key.clone());
905            }
906            if let Some(role_arn) = &self.s3_iam_role_arn {
907                iceberg_configs.insert(S3_ASSUME_ROLE_ARN.to_owned(), role_arn.clone());
908            }
909            if let Some(gcs_credential) = &self.gcs_credential {
910                iceberg_configs.insert(GCS_CREDENTIALS_JSON.to_owned(), gcs_credential.clone());
911                require_rest("gcs")?;
912            }
913
914            if let (
915                Some(azblob_account_name),
916                Some(azblob_account_key),
917                Some(azblob_endpoint_url),
918            ) = (
919                &self.azblob_account_name,
920                &self.azblob_account_key,
921                &self.azblob_endpoint_url,
922            ) {
923                iceberg_configs.insert(AZBLOB_ACCOUNT_NAME.to_owned(), azblob_account_name.clone());
924                iceberg_configs.insert(AZBLOB_ACCOUNT_KEY.to_owned(), azblob_account_key.clone());
925                iceberg_configs.insert(AZBLOB_ENDPOINT.to_owned(), azblob_endpoint_url.clone());
926
927                require_rest("azblob")?;
928            }
929
930            let adls_props = self.adls_file_io_props()?;
931            if !adls_props.is_empty() {
932                require_rest("adlsgen2")?;
933                iceberg_configs.extend(adls_props);
934            }
935
936            match &self.warehouse_path {
937                Some(warehouse_path) => {
938                    let (bucket, _) = {
939                        let is_s3_tables = warehouse_path.starts_with("arn:aws:s3tables");
940                        // Lakehouse Iceberg REST catalog federation uses bq:// prefix for BigQuery-managed Iceberg tables.
941                        let is_bq_catalog_federation = warehouse_path.starts_with("bq://");
942                        let url = Url::parse(warehouse_path);
943                        if (url.is_err() || is_s3_tables || is_bq_catalog_federation)
944                            && catalog_impl == JniCatalogImpl::Rest
945                        {
946                            // If the warehouse path is not a valid URL, it could be:
947                            // - A warehouse name in REST catalog
948                            // - An S3 Tables path (arn:aws:s3tables:...)
949                            // - A Lakehouse path (bq://projects/...) for Google Cloud BigQuery integration
950                            // We allow these to pass through for REST catalogs.
951                            (None, None)
952                        } else {
953                            let url = url.with_context(|| {
954                                format!("Invalid warehouse path: {}", warehouse_path)
955                            })?;
956                            let bucket = url
957                                .host_str()
958                                .with_context(|| {
959                                    format!(
960                                        "Invalid s3 path: {}, bucket is missing",
961                                        warehouse_path
962                                    )
963                                })?
964                                .to_owned();
965                            let root = url.path().trim_start_matches('/').to_owned();
966                            (Some(bucket), Some(root))
967                        }
968                    };
969
970                    if let Some(bucket) = bucket {
971                        iceberg_configs.insert("iceberg.table.io.bucket".to_owned(), bucket);
972                    }
973                }
974                None => {
975                    if catalog_impl != JniCatalogImpl::Rest {
976                        bail!("`warehouse.path` must be set in {} catalog", catalog_type);
977                    }
978                }
979            }
980            iceberg_configs.insert(
981                S3_DISABLE_CONFIG_LOAD.to_owned(),
982                (!enable_config_load).to_string(),
983            );
984
985            iceberg_configs.insert(
986                GCS_DISABLE_CONFIG_LOAD.to_owned(),
987                (!enable_config_load).to_string(),
988            );
989
990            iceberg_configs.insert(
991                S3_PATH_STYLE_ACCESS.to_owned(),
992                self.effective_s3_path_style_access().to_string(),
993            );
994
995            iceberg_configs
996        };
997
998        // Prepare jni configs, for details please see https://iceberg.apache.org/docs/latest/aws/
999        let mut java_catalog_configs = HashMap::new();
1000        {
1001            if let Some(uri) = self.catalog_uri.as_deref() {
1002                java_catalog_configs.insert("uri".to_owned(), uri.to_owned());
1003            }
1004
1005            if let Some(warehouse_path) = &self.warehouse_path {
1006                java_catalog_configs.insert("warehouse".to_owned(), warehouse_path.clone());
1007            }
1008            java_catalog_configs.extend(java_catalog_props.clone());
1009
1010            // Set io-impl: use custom io-impl if provided, otherwise default to S3FileIO
1011            let io_impl = self
1012                .catalog_io_impl
1013                .clone()
1014                .unwrap_or_else(|| "org.apache.iceberg.aws.s3.S3FileIO".to_owned());
1015            java_catalog_configs.insert("io-impl".to_owned(), io_impl);
1016
1017            // suppress log of FileIO like: Unclosed FileIO instance created by...
1018            java_catalog_configs.insert("init-creation-stacktrace".to_owned(), "false".to_owned());
1019
1020            if let Some(region) = &self.s3_region {
1021                java_catalog_configs.insert("client.region".to_owned(), region.clone());
1022            }
1023            if let Some(endpoint) = &self.s3_endpoint {
1024                java_catalog_configs.insert("s3.endpoint".to_owned(), endpoint.clone());
1025            }
1026
1027            if let Some(access_key) = &self.s3_access_key {
1028                java_catalog_configs.insert("s3.access-key-id".to_owned(), access_key.clone());
1029            }
1030            if let Some(secret_key) = &self.s3_secret_key {
1031                java_catalog_configs.insert("s3.secret-access-key".to_owned(), secret_key.clone());
1032            }
1033
1034            if let Some(path_style_access) = &self.s3_path_style_access {
1035                java_catalog_configs.insert(
1036                    "s3.path-style-access".to_owned(),
1037                    path_style_access.to_string(),
1038                );
1039            }
1040
1041            let headers = self.headers()?;
1042            for (header_name, header_value) in headers {
1043                java_catalog_configs.insert(format!("header.{}", header_name), header_value);
1044            }
1045
1046            match catalog_impl {
1047                JniCatalogImpl::Rest => {
1048                    // Handle security type for REST catalog (Iceberg 1.10+)
1049                    if let Some(security) = &self.catalog_security {
1050                        match security.to_lowercase().as_str() {
1051                            "google" => {
1052                                // Google AuthManager (Iceberg 1.10+) - uses Google ADC
1053                                java_catalog_configs.insert(
1054                                    "rest.auth.type".to_owned(),
1055                                    "org.apache.iceberg.gcp.auth.GoogleAuthManager".to_owned(),
1056                                );
1057                                // Set GCP auth scopes if provided
1058                                if let Some(gcp_auth_scopes) = &self.gcp_auth_scopes {
1059                                    java_catalog_configs.insert(
1060                                        "gcp.auth.scopes".to_owned(),
1061                                        gcp_auth_scopes.clone(),
1062                                    );
1063                                }
1064                            }
1065                            "oauth2" => {
1066                                // Standard OAuth2 authentication
1067                                if let Some(credential) = &self.catalog_credential {
1068                                    java_catalog_configs
1069                                        .insert("credential".to_owned(), credential.clone());
1070                                }
1071                                if let Some(token) = &self.catalog_token {
1072                                    java_catalog_configs.insert("token".to_owned(), token.clone());
1073                                }
1074                                if let Some(oauth2_server_uri) = &self.catalog_oauth2_server_uri {
1075                                    java_catalog_configs.insert(
1076                                        "oauth2-server-uri".to_owned(),
1077                                        oauth2_server_uri.clone(),
1078                                    );
1079                                }
1080                                if let Some(scope) = &self.catalog_scope {
1081                                    java_catalog_configs.insert("scope".to_owned(), scope.clone());
1082                                }
1083                            }
1084                            "none" | "" => {
1085                                // No authentication
1086                            }
1087                            _ => {
1088                                tracing::warn!(
1089                                    "Unknown catalog.security value: {}. Supported values: none, oauth2, google",
1090                                    security
1091                                );
1092                            }
1093                        }
1094                    } else {
1095                        // Legacy behavior: use individual OAuth2 properties if security type not specified
1096                        if let Some(credential) = &self.catalog_credential {
1097                            java_catalog_configs
1098                                .insert("credential".to_owned(), credential.clone());
1099                        }
1100                        if let Some(token) = &self.catalog_token {
1101                            java_catalog_configs.insert("token".to_owned(), token.clone());
1102                        }
1103                        if let Some(oauth2_server_uri) = &self.catalog_oauth2_server_uri {
1104                            java_catalog_configs
1105                                .insert("oauth2-server-uri".to_owned(), oauth2_server_uri.clone());
1106                        }
1107                        if let Some(scope) = &self.catalog_scope {
1108                            java_catalog_configs.insert("scope".to_owned(), scope.clone());
1109                        }
1110                    }
1111                    if let Some(rest_signing_region) = &self.rest_signing_region {
1112                        java_catalog_configs.insert(
1113                            "rest.signing-region".to_owned(),
1114                            rest_signing_region.clone(),
1115                        );
1116                    }
1117                    if let Some(rest_signing_name) = &self.rest_signing_name {
1118                        java_catalog_configs
1119                            .insert("rest.signing-name".to_owned(), rest_signing_name.clone());
1120                    }
1121                    if self.rest_sigv4_enabled == Some(true) {
1122                        // Equivalent to the legacy `rest.sigv4-enabled=true`, which is
1123                        // deprecated since Iceberg 1.10 and warns on every catalog load.
1124                        java_catalog_configs
1125                            .insert("rest.auth.type".to_owned(), "sigv4".to_owned());
1126
1127                        if let Some(access_key) = &self.s3_access_key {
1128                            java_catalog_configs
1129                                .insert("rest.access-key-id".to_owned(), access_key.clone());
1130                        }
1131
1132                        if let Some(secret_key) = &self.s3_secret_key {
1133                            java_catalog_configs
1134                                .insert("rest.secret-access-key".to_owned(), secret_key.clone());
1135                        }
1136                    }
1137                    // Iceberg 1.10+ infers `rest.auth.type=oauth2` from `credential`/`token`
1138                    // when it is unset, warning on every catalog load. Set it explicitly.
1139                    if !java_catalog_configs.contains_key("rest.auth.type")
1140                        && (java_catalog_configs.contains_key("credential")
1141                            || java_catalog_configs.contains_key("token"))
1142                    {
1143                        java_catalog_configs
1144                            .insert("rest.auth.type".to_owned(), "oauth2".to_owned());
1145                    }
1146                }
1147                JniCatalogImpl::Glue => {
1148                    let glue_access_key = self.glue_access_key();
1149                    let glue_secret_key = self.glue_secret_key();
1150                    let has_glue_credentials =
1151                        glue_access_key.is_some() && glue_secret_key.is_some();
1152                    let should_configure_glue_provider = !enable_config_load
1153                        || has_glue_credentials
1154                        || self.glue_iam_role_arn.is_some();
1155
1156                    if should_configure_glue_provider {
1157                        java_catalog_configs.insert(
1158                            "client.credentials-provider".to_owned(),
1159                            "com.risingwave.connector.catalog.GlueCredentialProvider".to_owned(),
1160                        );
1161                        if let Some(region) = self.glue_region() {
1162                            java_catalog_configs.insert(
1163                                "client.credentials-provider.glue.region".to_owned(),
1164                                region.to_owned(),
1165                            );
1166                        }
1167                        if let Some(access_key) = glue_access_key {
1168                            java_catalog_configs.insert(
1169                                "client.credentials-provider.glue.access-key-id".to_owned(),
1170                                access_key.to_owned(),
1171                            );
1172                        }
1173                        if let Some(secret_key) = glue_secret_key {
1174                            java_catalog_configs.insert(
1175                                "client.credentials-provider.glue.secret-access-key".to_owned(),
1176                                secret_key.to_owned(),
1177                            );
1178                        }
1179                        if let Some(role_arn) = self.glue_iam_role_arn.as_deref() {
1180                            java_catalog_configs.insert(
1181                                "client.credentials-provider.glue.iam-role-arn".to_owned(),
1182                                role_arn.to_owned(),
1183                            );
1184                        }
1185                        if enable_config_load && !has_glue_credentials {
1186                            java_catalog_configs.insert(
1187                                "client.credentials-provider.glue.use-default-credential-chain"
1188                                    .to_owned(),
1189                                "true".to_owned(),
1190                            );
1191                        }
1192                    }
1193
1194                    if let Some(region) = self.glue_region() {
1195                        java_catalog_configs.insert("client.region".to_owned(), region.to_owned());
1196                    }
1197                    let glue_endpoint = self.glue_endpoint().map(str::to_owned).or_else(|| {
1198                        self.glue_region()
1199                            .map(|region| format!("https://glue.{}.amazonaws.com", region))
1200                    });
1201                    if let Some(endpoint) = glue_endpoint {
1202                        java_catalog_configs.insert("glue.endpoint".to_owned(), endpoint);
1203                    }
1204
1205                    if let Some(glue_id) = self.glue_id.as_deref() {
1206                        java_catalog_configs.insert("glue.id".to_owned(), glue_id.to_owned());
1207                    }
1208                    self.apply_java_s3_file_io_assume_role_configs(&mut java_catalog_configs);
1209                }
1210                JniCatalogImpl::Jdbc => {
1211                    self.apply_java_aws_client_assume_role_configs(&mut java_catalog_configs);
1212                }
1213                _ => {}
1214            }
1215        }
1216
1217        Ok((file_io_props, java_catalog_configs))
1218    }
1219
1220    fn apply_java_s3_file_io_assume_role_configs(
1221        &self,
1222        java_catalog_configs: &mut HashMap<String, String>,
1223    ) {
1224        if let Some(iam_role_arn) = &self.s3_iam_role_arn {
1225            java_catalog_configs.insert(
1226                "s3.client-factory-impl".to_owned(),
1227                "com.risingwave.connector.catalog.S3FileIOAssumeRoleAwsClientFactory".to_owned(),
1228            );
1229            java_catalog_configs.insert("s3.iam-role-arn".to_owned(), iam_role_arn.clone());
1230        }
1231    }
1232
1233    fn apply_java_aws_client_assume_role_configs(
1234        &self,
1235        java_catalog_configs: &mut HashMap<String, String>,
1236    ) {
1237        if let Some(iam_role_arn) = &self.s3_iam_role_arn {
1238            java_catalog_configs.insert("client.assume-role.arn".to_owned(), iam_role_arn.clone());
1239            java_catalog_configs.insert(
1240                "client.factory".to_owned(),
1241                "org.apache.iceberg.aws.AssumeRoleAwsClientFactory".to_owned(),
1242            );
1243            if let Some(region) = &self.s3_region {
1244                java_catalog_configs.insert("client.assume-role.region".to_owned(), region.clone());
1245            }
1246        }
1247    }
1248}
1249
1250/// Get a globally shared object cache keyed by table UUID to avoid reuse after drop & recreate.
1251pub(crate) async fn shared_object_cache(
1252    init_object_cache: Arc<ObjectCache>,
1253    table_uuid: Uuid,
1254) -> Arc<ObjectCache> {
1255    static CACHE: LazyLock<MokaCache<Uuid, Arc<ObjectCache>>> = LazyLock::new(|| {
1256        MokaCache::builder()
1257            .max_capacity(SHARED_OBJECT_CACHE_MAX_TABLES)
1258            .build()
1259    });
1260
1261    CACHE
1262        .get_with(table_uuid, async { init_object_cache })
1263        .await
1264}
1265
1266pub async fn rebuild_table_with_shared_cache(table: Table) -> Table {
1267    let table_uuid = table.metadata().uuid();
1268    let init_object_cache = table.object_cache();
1269    let object_cache = shared_object_cache(init_object_cache, table_uuid).await;
1270    table.with_object_cache(object_cache)
1271}
1272
1273#[cfg(test)]
1274mod tests {
1275    use std::collections::HashMap;
1276
1277    use super::*;
1278
1279    fn test_common(catalog_type: &str) -> IcebergCommon {
1280        IcebergCommon {
1281            catalog_type: Some(catalog_type.to_owned()),
1282            s3_region: Some("ap-southeast-2".to_owned()),
1283            s3_endpoint: None,
1284            s3_access_key: None,
1285            s3_secret_key: None,
1286            s3_iam_role_arn: None,
1287            glue_access_key: None,
1288            glue_secret_key: None,
1289            glue_iam_role_arn: None,
1290            glue_region: None,
1291            glue_endpoint: None,
1292            glue_id: None,
1293            gcs_credential: None,
1294            azblob_account_name: None,
1295            azblob_account_key: None,
1296            azblob_endpoint_url: None,
1297            adlsgen2_account_name: None,
1298            adlsgen2_account_key: None,
1299            adlsgen2_endpoint: None,
1300            adlsgen2_tenant_id: None,
1301            adlsgen2_client_id: None,
1302            adlsgen2_client_secret: None,
1303            adlsgen2_authority_host: None,
1304            warehouse_path: Some("s3://bucket/warehouse".to_owned()),
1305            catalog_name: None,
1306            catalog_uri: None,
1307            catalog_credential: None,
1308            catalog_token: None,
1309            catalog_oauth2_server_uri: None,
1310            catalog_scope: None,
1311            rest_signing_region: None,
1312            rest_signing_name: None,
1313            rest_sigv4_enabled: None,
1314            s3_path_style_access: None,
1315            enable_config_load: None,
1316            hosted_catalog: None,
1317            catalog_header: None,
1318            vended_credentials: None,
1319            catalog_security: None,
1320            gcp_auth_scopes: None,
1321            catalog_io_impl: None,
1322        }
1323    }
1324
1325    #[test]
1326    fn test_vended_rest_resolves_to_native_runtime_without_rewriting_catalog_type() {
1327        let common = IcebergCommon {
1328            vended_credentials: Some(true),
1329            ..test_common("rest")
1330        };
1331
1332        assert_eq!(common.catalog_type(), "rest");
1333        assert_eq!(
1334            common.resolve_catalog_kind().unwrap(),
1335            IcebergCatalogKind::Rest(IcebergCatalogRuntime::NativeRust)
1336        );
1337    }
1338
1339    #[test]
1340    fn test_rest_without_vended_credentials_resolves_to_jni_runtime() {
1341        let common = test_common("rest");
1342
1343        assert_eq!(
1344            common.resolve_catalog_kind().unwrap(),
1345            IcebergCatalogKind::Rest(IcebergCatalogRuntime::JavaJni)
1346        );
1347    }
1348
1349    #[test]
1350    fn test_gcs_vended_rest_catalog_passes_google_authentication() {
1351        let common = IcebergCommon {
1352            catalog_uri: Some("https://catalog.example".to_owned()),
1353            warehouse_path: Some("gs://bucket/warehouse".to_owned()),
1354            catalog_security: Some("google".to_owned()),
1355            gcp_auth_scopes: Some("scope-a,scope-b".to_owned()),
1356            gcs_credential: Some("service-account-json".to_owned()),
1357            catalog_header: Some("x-goog-user-project=billing-project".to_owned()),
1358            vended_credentials: Some(true),
1359            ..test_common("rest")
1360        };
1361        assert_eq!(
1362            common.resolve_catalog_kind().unwrap(),
1363            IcebergCatalogKind::Rest(IcebergCatalogRuntime::NativeRust)
1364        );
1365        let CatalogBuildPlan::NativeRest(props) = common.build_native_rest_catalog_props().unwrap()
1366        else {
1367            panic!("expected native REST catalog");
1368        };
1369        assert_eq!(props["rest.auth.type"], "google");
1370        assert_eq!(props["gcp.auth.scopes"], "scope-a,scope-b");
1371        assert_eq!(props[GCS_CREDENTIALS_JSON], "service-account-json");
1372        assert_eq!(props["warehouse"], "gs://bucket/warehouse");
1373        assert_eq!(
1374            props["header.X-Iceberg-Access-Delegation"],
1375            "vended-credentials"
1376        );
1377        assert_eq!(props["header.x-goog-user-project"], "billing-project");
1378        assert!(!props.contains_key("io-impl"));
1379    }
1380
1381    #[test]
1382    fn test_native_google_catalog_supports_adc_without_storage_credentials() {
1383        let common = IcebergCommon {
1384            catalog_uri: Some("https://catalog.example".to_owned()),
1385            catalog_security: Some("google".to_owned()),
1386            vended_credentials: Some(true),
1387            ..test_common("rest_rust")
1388        };
1389        let CatalogBuildPlan::NativeRest(props) = common.build_native_rest_catalog_props().unwrap()
1390        else {
1391            panic!("expected native REST catalog");
1392        };
1393        assert_eq!(props["rest.auth.type"], "google");
1394        assert!(!props.contains_key(GCS_CREDENTIALS_JSON));
1395        assert!(!props.contains_key("gcp.auth.scopes"));
1396    }
1397
1398    #[test]
1399    fn test_native_google_catalog_rejects_adc_when_default_credentials_disabled() {
1400        for security in ["google", "GoOgLe"] {
1401            for (credential, token) in [
1402                (None, None),
1403                (Some("client:secret"), None),
1404                (None, Some("catalog-token")),
1405                (Some("client:secret"), Some("catalog-token")),
1406            ] {
1407                let common = IcebergCommon {
1408                    catalog_security: Some(security.to_owned()),
1409                    catalog_credential: credential.map(str::to_owned),
1410                    catalog_token: token.map(str::to_owned),
1411                    ..test_common("rest_rust")
1412                };
1413                assert_eq!(
1414                    common
1415                        .validate_native_rest_catalog_auth(true)
1416                        .unwrap_err()
1417                        .to_string(),
1418                    "`catalog.security=google` requires `gcs.credential` when `DISABLE_DEFAULT_CREDENTIAL=true`"
1419                );
1420                common.validate_native_rest_catalog_auth(false).unwrap();
1421
1422                let common = IcebergCommon {
1423                    gcs_credential: Some("service-account-json".to_owned()),
1424                    ..common
1425                };
1426                common.validate_native_rest_catalog_auth(true).unwrap();
1427            }
1428        }
1429    }
1430
1431    #[test]
1432    fn test_native_non_google_catalog_auth_does_not_require_gcs_credentials() {
1433        for security in [None, Some("none"), Some("oauth2")] {
1434            let common = IcebergCommon {
1435                catalog_security: security.map(str::to_owned),
1436                ..test_common("rest_rust")
1437            };
1438            common.validate_native_rest_catalog_auth(true).unwrap();
1439        }
1440    }
1441
1442    #[test]
1443    fn test_s3_path_style_access_preserves_existing_default() {
1444        let common = test_common("storage");
1445        assert!(common.effective_s3_path_style_access());
1446
1447        let common = IcebergCommon {
1448            s3_path_style_access: Some(false),
1449            ..common
1450        };
1451        assert!(!common.effective_s3_path_style_access());
1452    }
1453
1454    #[test]
1455    fn test_mock_v3_resolves_to_mock_catalog_for_simulation_tests() {
1456        let common = test_common("mock_v3");
1457
1458        assert_eq!(
1459            common.resolve_catalog_kind().unwrap(),
1460            IcebergCatalogKind::Mock
1461        );
1462    }
1463
1464    #[test]
1465    fn test_extract_java_catalog_props_keeps_wire_options_flat() {
1466        let options = HashMap::from([
1467            ("catalog.type".to_owned(), "rest".to_owned()),
1468            ("catalog.uri".to_owned(), "http://localhost:8181".to_owned()),
1469            ("catalog.name".to_owned(), "demo".to_owned()),
1470            ("catalog.header".to_owned(), "x=y".to_owned()),
1471            (
1472                "catalog.rest.signing_region".to_owned(),
1473                "us-east-1".to_owned(),
1474            ),
1475            ("catalog.jdbc.user".to_owned(), "rw".to_owned()),
1476        ]);
1477
1478        let java_props = iceberg_java_catalog_props_from_options(
1479            options
1480                .iter()
1481                .map(|(key, value)| (key.as_str(), value.as_str())),
1482        );
1483
1484        assert_eq!(java_props.get("rest.signing_region").unwrap(), "us-east-1");
1485        assert_eq!(java_props.get("jdbc.user").unwrap(), "rw");
1486        assert!(!java_props.contains_key("type"));
1487        assert!(!java_props.contains_key("uri"));
1488        assert!(!java_props.contains_key("name"));
1489        assert!(!java_props.contains_key("header"));
1490    }
1491
1492    #[test]
1493    fn test_glue_jni_catalog_uses_s3_assume_role_for_file_io() {
1494        let common = IcebergCommon {
1495            s3_iam_role_arn: Some("arn:aws:iam::123456789012:role/risingwave-s3".to_owned()),
1496            ..test_common("glue")
1497        };
1498
1499        let (_, java_catalog_configs) = common
1500            .build_jni_catalog_configs(JniCatalogImpl::Glue, &HashMap::new())
1501            .unwrap();
1502
1503        assert_eq!(
1504            java_catalog_configs.get("s3.client-factory-impl").unwrap(),
1505            "com.risingwave.connector.catalog.S3FileIOAssumeRoleAwsClientFactory"
1506        );
1507        assert_eq!(
1508            java_catalog_configs.get("s3.iam-role-arn").unwrap(),
1509            "arn:aws:iam::123456789012:role/risingwave-s3"
1510        );
1511        assert!(!java_catalog_configs.contains_key("client.factory"));
1512    }
1513
1514    #[test]
1515    fn test_rest_jni_catalog_sets_auth_type_explicitly() {
1516        let build = |common: IcebergCommon, props: &[(&str, &str)]| {
1517            let props = props
1518                .iter()
1519                .map(|(k, v)| ((*k).to_owned(), (*v).to_owned()))
1520                .collect();
1521            common
1522                .build_jni_catalog_configs(JniCatalogImpl::Rest, &props)
1523                .unwrap()
1524                .1
1525        };
1526        let oauth2 = IcebergCommon {
1527            catalog_credential: Some("client-id:client-secret".to_owned()),
1528            rest_sigv4_enabled: Some(false),
1529            ..test_common("rest")
1530        };
1531
1532        let configs = build(oauth2.clone(), &[]);
1533        assert_eq!(configs.get("rest.auth.type").unwrap(), "oauth2");
1534        assert!(!configs.contains_key("rest.sigv4-enabled"));
1535
1536        let configs = build(oauth2, &[("rest.auth.type", "basic")]);
1537        assert_eq!(configs.get("rest.auth.type").unwrap(), "basic");
1538
1539        let sigv4 = IcebergCommon {
1540            catalog_token: Some("token".to_owned()),
1541            rest_sigv4_enabled: Some(true),
1542            ..test_common("rest")
1543        };
1544        let configs = build(sigv4, &[]);
1545        assert_eq!(configs.get("rest.auth.type").unwrap(), "sigv4");
1546        assert!(!configs.contains_key("rest.sigv4-enabled"));
1547    }
1548
1549    #[test]
1550    fn test_adlsgen2_service_principal_populates_file_io_configs_with_default_authority_host() {
1551        let common = test_adlsgen2_service_principal_common(None);
1552
1553        let (file_io_props, _) = common
1554            .build_jni_catalog_configs(JniCatalogImpl::Rest, &HashMap::new())
1555            .unwrap();
1556
1557        assert_eq!(file_io_props.get(ADLS_TENANT_ID).unwrap(), "tenant-uuid");
1558        assert_eq!(file_io_props.get(ADLS_CLIENT_ID).unwrap(), "client-uuid");
1559        assert_eq!(
1560            file_io_props.get(ADLS_CLIENT_SECRET).unwrap(),
1561            "secret-value"
1562        );
1563        assert_eq!(
1564            file_io_props.get(ADLS_AUTHORITY_HOST).unwrap(),
1565            ADLS_DEFAULT_AUTHORITY_HOST
1566        );
1567    }
1568
1569    fn test_adlsgen2_service_principal_common(authority_host: Option<&str>) -> IcebergCommon {
1570        IcebergCommon {
1571            adlsgen2_account_name: Some("acct".to_owned()),
1572            adlsgen2_tenant_id: Some("tenant-uuid".to_owned()),
1573            adlsgen2_client_id: Some("client-uuid".to_owned()),
1574            adlsgen2_client_secret: Some("secret-value".to_owned()),
1575            adlsgen2_authority_host: authority_host.map(str::to_owned),
1576            catalog_uri: Some("http://localhost:8181".to_owned()),
1577            warehouse_path: Some("abfss://wh@acct.dfs.core.windows.net/wh".to_owned()),
1578            ..test_common("rest")
1579        }
1580    }
1581
1582    #[test]
1583    fn test_adlsgen2_service_principal_authority_host_override_is_respected() {
1584        let common =
1585            test_adlsgen2_service_principal_common(Some("https://login.microsoftonline.us"));
1586
1587        let (file_io_props, _) = common
1588            .build_jni_catalog_configs(JniCatalogImpl::Rest, &HashMap::new())
1589            .unwrap();
1590
1591        assert_eq!(
1592            file_io_props.get(ADLS_AUTHORITY_HOST).unwrap(),
1593            "https://login.microsoftonline.us"
1594        );
1595    }
1596
1597    #[test]
1598    fn test_adlsgen2_authority_host_rejects_non_bare_https_origins() {
1599        let cases = [
1600            ("not a url", "does not parse as a URL"),
1601            (
1602                "http://login.microsoftonline.com",
1603                "must use the https scheme",
1604            ),
1605            (
1606                "https://user:pass@login.microsoftonline.com",
1607                "must not contain userinfo",
1608            ),
1609            (
1610                "https://login.microsoftonline.com?bar=baz",
1611                "must not contain a query or fragment",
1612            ),
1613            (
1614                "https://login.microsoftonline.com#frag",
1615                "must not contain a query or fragment",
1616            ),
1617            (
1618                "https://login.microsoftonline.com/foo",
1619                "must not contain a path component",
1620            ),
1621        ];
1622        for (authority_host, expected_error) in cases {
1623            let common = test_adlsgen2_service_principal_common(Some(authority_host));
1624            let err = common
1625                .build_jni_catalog_configs(JniCatalogImpl::Rest, &HashMap::new())
1626                .unwrap_err();
1627            assert!(
1628                format!("{:#}", err).contains(expected_error),
1629                "authority_host {authority_host:?}: expected error containing {expected_error:?}, got: {err:#}"
1630            );
1631        }
1632    }
1633
1634    #[test]
1635    fn test_adlsgen2_authority_host_trailing_slash_is_normalized() {
1636        let common =
1637            test_adlsgen2_service_principal_common(Some("https://login.microsoftonline.us/"));
1638
1639        let (file_io_props, _) = common
1640            .build_jni_catalog_configs(JniCatalogImpl::Rest, &HashMap::new())
1641            .unwrap();
1642
1643        assert_eq!(
1644            file_io_props.get(ADLS_AUTHORITY_HOST).unwrap(),
1645            "https://login.microsoftonline.us"
1646        );
1647    }
1648
1649    #[test]
1650    fn test_adlsgen2_rejects_mixing_shared_key_and_service_principal() {
1651        let common = IcebergCommon {
1652            adlsgen2_account_key: Some("shared-key".to_owned()),
1653            ..test_adlsgen2_service_principal_common(None)
1654        };
1655
1656        let err = common
1657            .build_jni_catalog_configs(JniCatalogImpl::Rest, &HashMap::new())
1658            .unwrap_err();
1659        assert!(
1660            format!("{:#}", err).contains("exactly one auth mode"),
1661            "expected mutual-exclusion error, got: {err:#}"
1662        );
1663    }
1664
1665    #[test]
1666    fn test_adlsgen2_rejects_partial_service_principal_config() {
1667        let common = IcebergCommon {
1668            adlsgen2_client_secret: None,
1669            ..test_adlsgen2_service_principal_common(None)
1670        };
1671
1672        let err = common
1673            .build_jni_catalog_configs(JniCatalogImpl::Rest, &HashMap::new())
1674            .unwrap_err();
1675        assert!(
1676            format!("{:#}", err).contains("requires all three"),
1677            "expected partial-config error, got: {err:#}"
1678        );
1679    }
1680
1681    #[test]
1682    fn test_iceberg_table_identifier_validation() {
1683        let valid_identifier = IcebergTableIdentifier {
1684            database_name: Some("valid_db".to_owned()),
1685            table_name: "test_table".to_owned(),
1686        };
1687        assert!(valid_identifier.validate().is_ok());
1688
1689        let valid_underscore = IcebergTableIdentifier {
1690            database_name: Some("valid_db_name".to_owned()),
1691            table_name: "test_table".to_owned(),
1692        };
1693        assert!(valid_underscore.validate().is_ok());
1694
1695        let no_database = IcebergTableIdentifier {
1696            database_name: None,
1697            table_name: "test_table".to_owned(),
1698        };
1699        assert!(no_database.validate().is_ok());
1700
1701        let empty_part = IcebergTableIdentifier {
1702            database_name: Some("a..b".to_owned()),
1703            table_name: "test_table".to_owned(),
1704        };
1705        let result = empty_part.validate();
1706        assert!(result.is_err());
1707        assert!(
1708            result
1709                .unwrap_err()
1710                .to_string()
1711                .contains("identifier parts must not be empty")
1712        );
1713
1714        let leading_dot = IcebergTableIdentifier {
1715            database_name: None,
1716            table_name: ".test_table".to_owned(),
1717        };
1718        let result = leading_dot.validate();
1719        assert!(result.is_err());
1720        assert!(
1721            result
1722                .unwrap_err()
1723                .to_string()
1724                .contains("identifier parts must not be empty")
1725        );
1726    }
1727
1728    #[test]
1729    fn test_iceberg_table_identifier_dots_as_namespace_separators() {
1730        let table_ident = IcebergTableIdentifier {
1731            database_name: Some("general.zia.stats".to_owned()),
1732            table_name: "tagged_security_transactions".to_owned(),
1733        }
1734        .to_table_ident()
1735        .unwrap();
1736        let namespace: Vec<_> = table_ident
1737            .namespace()
1738            .as_ref()
1739            .iter()
1740            .map(String::as_str)
1741            .collect();
1742        assert_eq!(namespace, vec!["general", "zia", "stats"]);
1743        assert_eq!(table_ident.name(), "tagged_security_transactions");
1744
1745        let table_ident = IcebergTableIdentifier {
1746            database_name: Some("general".to_owned()),
1747            table_name: "zia.stats.tagged_security_transactions".to_owned(),
1748        }
1749        .to_table_ident()
1750        .unwrap();
1751        let namespace: Vec<_> = table_ident
1752            .namespace()
1753            .as_ref()
1754            .iter()
1755            .map(String::as_str)
1756            .collect();
1757        assert_eq!(namespace, vec!["general", "zia", "stats"]);
1758        assert_eq!(table_ident.name(), "tagged_security_transactions");
1759
1760        let table_ident = IcebergTableIdentifier {
1761            database_name: None,
1762            table_name: "general.zia.stats.tagged_security_transactions".to_owned(),
1763        }
1764        .to_table_ident()
1765        .unwrap();
1766        let namespace: Vec<_> = table_ident
1767            .namespace()
1768            .as_ref()
1769            .iter()
1770            .map(String::as_str)
1771            .collect();
1772        assert_eq!(namespace, vec!["general", "zia", "stats"]);
1773        assert_eq!(table_ident.name(), "tagged_security_transactions");
1774    }
1775}