Skip to main content

mz_storage_types/
connections.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10//! Connection types.
11
12use std::borrow::Cow;
13use std::collections::{BTreeMap, BTreeSet};
14use std::fmt;
15use std::net::SocketAddr;
16use std::sync::Arc;
17use std::time::SystemTime;
18
19use anyhow::{Context, anyhow};
20use async_trait::async_trait;
21use aws_credential_types::provider::{ProvideCredentials, SharedCredentialsProvider};
22use aws_sigv4::http_request::{SignableBody, SignableRequest, SigningSettings, sign};
23use aws_sigv4::sign::v4;
24// Aliased to avoid colliding with `mz_ccsr::tls::Identity`.
25use aws_smithy_runtime_api::client::identity::Identity as AwsIdentity;
26use base64::Engine;
27use http::{HeaderMap, HeaderName, HeaderValue};
28use iceberg::Catalog;
29use iceberg::CatalogBuilder;
30use iceberg::TableIdent;
31use iceberg::io::{
32    GCS_CREDENTIALS_JSON, GCS_DISABLE_CONFIG_LOAD, GCS_DISABLE_VM_METADATA, GCS_USER_PROJECT,
33    S3_ACCESS_KEY_ID, S3_DISABLE_EC2_METADATA, S3_REGION, S3_SECRET_ACCESS_KEY,
34};
35use iceberg_catalog_rest::{
36    OAuth2TokenProvider, REST_CATALOG_PROP_URI, REST_CATALOG_PROP_WAREHOUSE, RequestAuthenticator,
37    RestCatalogBuilder, TokenProvider,
38};
39use iceberg_storage_opendal::{
40    AwsCredential, CustomAwsCredentialLoader, CustomAzdlsCredentialLoader,
41    CustomGcsCredentialLoader, OpenDalStorageFactory, ProvideCredential,
42};
43use itertools::Itertools;
44use mz_ccsr::tls::{Certificate, Identity};
45use mz_cloud_resources::{AwsExternalIdPrefix, CloudResourceReader, vpc_endpoint_host};
46use mz_dyncfg::ConfigSet;
47use mz_kafka_util::client::{
48    BrokerAddr, BrokerRewrite, HostMappingRules, MzClientContext, MzKafkaError, TunnelConfig,
49    TunnelingClientContext,
50};
51use mz_mysql_util::{MySqlConn, MySqlError};
52use mz_ore::assert_none;
53use mz_ore::error::ErrorExt;
54use mz_ore::future::{InTask, OreFutureExt};
55use mz_ore::netio::resolve_address;
56use mz_ore::num::NonNeg;
57use mz_ore::str::StrExt;
58use mz_repr::{CatalogItemId, GlobalId};
59use mz_secrets::SecretsReader;
60use mz_sql_parser::ast::ConnectionRulePattern;
61use mz_ssh_util::keys::SshKeyPair;
62use mz_ssh_util::tunnel::SshTunnelConfig;
63use mz_ssh_util::tunnel_manager::{ManagedSshTunnelHandle, SshTunnelManager};
64use mz_tracing::CloneableEnvFilter;
65use rdkafka::ClientContext;
66use rdkafka::config::FromClientConfigAndContext;
67use rdkafka::consumer::{BaseConsumer, Consumer};
68use regex::Regex;
69use reqsign_core::time::Timestamp;
70use reqwest_0_12::Request;
71use serde::{Deserialize, Deserializer, Serialize};
72use tokio::net;
73use tokio::runtime::Handle;
74use tokio_postgres::config::SslMode;
75use tracing::{debug, info, warn};
76use url::Url;
77
78use crate::AlterCompatible;
79use crate::configuration::StorageConfiguration;
80use crate::connections::aws::{
81    AwsAuth, AwsConnection, AwsConnectionReference, AwsConnectionValidationError,
82    AwsCredentialsCache,
83};
84use crate::connections::gcp::{GcpConnectionReference, GcpTokenProvider};
85use crate::connections::string_or_secret::StringOrSecret;
86use crate::controller::AlterError;
87use crate::dyncfgs::{
88    ENFORCE_EXTERNAL_ADDRESSES, KAFKA_CLIENT_ID_ENRICHMENT_RULES,
89    KAFKA_DEFAULT_AWS_PRIVATELINK_ENDPOINT_IDENTIFICATION_ALGORITHM, KAFKA_RECONNECT_BACKOFF,
90    KAFKA_RECONNECT_BACKOFF_MAX, KAFKA_RETRY_BACKOFF, KAFKA_RETRY_BACKOFF_MAX,
91};
92use crate::errors::{ContextCreationError, CsrConnectError};
93
94pub mod aws;
95pub mod gcp;
96mod iceberg_credentials;
97pub mod inline;
98pub mod string_or_secret;
99
100/// The OAuth2 form field naming the scopes a token is requested for.
101///
102/// Materialize drives the OAuth2 exchange itself rather than through the `credential`,
103/// `oauth2-server-uri`, and `scope` catalog properties, so that one token object serves both
104/// catalog requests and storage-credential refreshes.
105const OAUTH2_PARAM_SCOPE: &str = "scope";
106
107const REST_CATALOG_PROP_OAUTH2_SERVER_URI: &str = "oauth2-server-uri";
108/// The prefix marking a catalog property that `iceberg-rust` turns into a header on every REST
109/// request, the same convention the Iceberg Java client uses.
110const REST_CATALOG_HEADER_PROP_PREFIX: &str = "header.";
111/// Requests catalog-vended storage credentials, carried as a header by way of
112/// [`REST_CATALOG_HEADER_PROP_PREFIX`].
113const REST_CATALOG_PROP_ACCESS_DELEGATION: &str = "header.X-Iceberg-Access-Delegation";
114
115/// A credential loader that wraps an aws-sdk-rust credentials provider for use with
116/// iceberg/OpenDAL. This allows us to provide refreshable credentials from the AWS SDK
117/// credential chain (including the full assume role chain) to OpenDAL's S3 implementation.
118///
119/// We use this instead of OpenDAL's built-in assume role support because Materialize
120/// has a runtime-defined credential chain (ambient → jump role → user role with external ID)
121/// that can't be expressed via OpenDAL's static configuration properties.
122#[derive(Debug)]
123struct AwsSdkCredentialLoader {
124    /// The underlying AWS SDK credentials provider. For assume role auth, this provider
125    /// already handles the full chain: ambient creds -> jump role -> user role.
126    provider: SharedCredentialsProvider,
127}
128
129impl AwsSdkCredentialLoader {
130    fn new(provider: SharedCredentialsProvider) -> Self {
131        Self { provider }
132    }
133}
134
135impl ProvideCredential for AwsSdkCredentialLoader {
136    type Credential = AwsCredential;
137
138    async fn provide_credential(
139        &self,
140        _ctx: &reqsign_core::Context,
141    ) -> reqsign_core::Result<Option<Self::Credential>> {
142        let creds = self.provider.provide_credentials().await.map_err(|e| {
143            warn!(
144                error = %e.display_with_causes(),
145                "failed to load AWS credentials for Iceberg FileIO from SDK provider"
146            );
147            reqsign_core::Error::credential_invalid(
148                "failed to load AWS credentials from SDK provider for Iceberg FileIO \
149                 (credential source may be temporarily unavailable)",
150            )
151            .with_source(e)
152        })?;
153
154        // Propagate the SDK's expiry whenever it reports one. reqsign treats a `None` expiry as
155        // "valid forever", so dropping it would leave OpenDAL signing with stale assume-role
156        // credentials rather than asking us for fresh ones.
157        let expires_in = creds.expiry().map(aws_expiry_to_timestamp).transpose()?;
158
159        Ok(Some(AwsCredential {
160            access_key_id: creds.access_key_id().to_string(),
161            secret_access_key: creds.secret_access_key().to_string(),
162            session_token: creds.session_token().map(|s| s.to_string()),
163            expires_in,
164        }))
165    }
166}
167
168/// Converts an AWS SDK credential expiry into reqsign's [`Timestamp`].
169///
170/// Both failure modes require a nonsensical expiry (before the Unix epoch, or beyond year
171/// 292278994), so they are reported as errors rather than silently dropped, which would make the
172/// credential look non-expiring.
173fn aws_expiry_to_timestamp(expiry: SystemTime) -> reqsign_core::Result<Timestamp> {
174    let millis = expiry
175        .duration_since(SystemTime::UNIX_EPOCH)
176        .map_err(|e| {
177            reqsign_core::Error::unexpected("AWS credential expiry precedes the Unix epoch")
178                .with_source(e)
179        })?
180        .as_millis();
181    let millis = i64::try_from(millis).map_err(|e| {
182        reqsign_core::Error::unexpected("AWS credential expiry overflows a millisecond timestamp")
183            .with_source(e)
184    })?;
185    Timestamp::from_millisecond(millis)
186}
187
188/// Signs each outgoing REST-catalog request with AWS SigV4.
189///
190/// Holds a [`SharedCredentialsProvider`] (not static `Credentials`) so each
191/// request signs with refreshable creds from Materialize's chain
192/// (ambient -> jump role -> user role w/ external ID).
193struct Sigv4Authenticator {
194    provider: SharedCredentialsProvider,
195    region: String,
196    /// The AWS signing name. `"s3tables"` for AWS S3 Tables REST catalog.
197    signing_name: String,
198}
199
200impl std::fmt::Debug for Sigv4Authenticator {
201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202        f.debug_struct("Sigv4Authenticator")
203            .field("region", &self.region)
204            .field("signing_name", &self.signing_name)
205            .finish_non_exhaustive()
206    }
207}
208
209fn sigv4_err(e: impl Into<anyhow::Error>) -> iceberg::Error {
210    iceberg::Error::new(iceberg::ErrorKind::DataInvalid, "AWS SigV4").with_source(e)
211}
212
213#[async_trait]
214impl RequestAuthenticator for Sigv4Authenticator {
215    async fn authenticate_request(&self, req: &mut Request) -> iceberg::Result<()> {
216        let creds = self
217            .provider
218            .provide_credentials()
219            .await
220            .map_err(sigv4_err)?;
221        let identity: AwsIdentity = creds.into();
222        let params = v4::SigningParams::builder()
223            .identity(&identity)
224            .region(&self.region)
225            .name(&self.signing_name)
226            .time(SystemTime::now())
227            .settings(SigningSettings::default())
228            .build()
229            .map_err(sigv4_err)?
230            .into();
231        let body: &[u8] = req
232            .body()
233            .map(|b| match b.as_bytes() {
234                Some(b) => Ok(b),
235                None => Err(iceberg::Error::new(
236                    iceberg::ErrorKind::FeatureUnsupported,
237                    "SigV4 Authenticator cannot sign a streaming request body.",
238                )),
239            })
240            .transpose()?
241            .unwrap_or_default();
242        let headers = req
243            .headers()
244            .iter()
245            .map(|(k, v)| {
246                Ok((
247                    k.as_str(),
248                    v.to_str().map_err(|_| {
249                        iceberg::Error::new(
250                            iceberg::ErrorKind::DataInvalid,
251                            format!("header '{}' value is not all visible ASCII", k),
252                        )
253                    })?,
254                ))
255            })
256            .collect::<iceberg::Result<Vec<(&str, &str)>>>()?;
257        let signable = SignableRequest::new(
258            req.method().as_str(),
259            req.url().as_str(),
260            headers.into_iter(),
261            SignableBody::Bytes(body),
262        )
263        .map_err(sigv4_err)?;
264        let (instructions, _sig) = sign(signable, &params).map_err(sigv4_err)?.into_parts();
265        let (new_headers, new_query) = instructions.into_parts();
266        for header in new_headers {
267            let mut value = HeaderValue::from_str(header.value()).map_err(sigv4_err)?;
268            value.set_sensitive(header.sensitive());
269            req.headers_mut()
270                .insert(HeaderName::from_static(header.name()), value);
271        }
272        if !new_query.is_empty() {
273            let url = req.url_mut();
274            let mut pairs = url.query_pairs_mut();
275            for (name, value) in new_query {
276                pairs.append_pair(name, &value);
277            }
278        }
279        Ok(())
280    }
281
282    // SigV4 is stateless: nothing to cache, invalidate, or refresh.
283    async fn invalidate_cache(&self) -> iceberg::Result<()> {
284        Ok(())
285    }
286    async fn regenerate_cache(&self) -> iceberg::Result<()> {
287        Ok(())
288    }
289}
290
291/// An extension trait for [`SecretsReader`]
292#[async_trait::async_trait]
293trait SecretsReaderExt {
294    /// `SecretsReader::read`, but optionally run in a task.
295    async fn read_in_task_if(
296        &self,
297        in_task: InTask,
298        id: CatalogItemId,
299    ) -> Result<Vec<u8>, anyhow::Error>;
300
301    /// `SecretsReader::read_string`, but optionally run in a task.
302    async fn read_string_in_task_if(
303        &self,
304        in_task: InTask,
305        id: CatalogItemId,
306    ) -> Result<String, anyhow::Error>;
307}
308
309#[async_trait::async_trait]
310impl SecretsReaderExt for Arc<dyn SecretsReader> {
311    async fn read_in_task_if(
312        &self,
313        in_task: InTask,
314        id: CatalogItemId,
315    ) -> Result<Vec<u8>, anyhow::Error> {
316        let sr = Arc::clone(self);
317        async move { sr.read(id).await }
318            .run_in_task_if(in_task, || "secrets_reader_read".to_string())
319            .await
320    }
321    async fn read_string_in_task_if(
322        &self,
323        in_task: InTask,
324        id: CatalogItemId,
325    ) -> Result<String, anyhow::Error> {
326        let sr = Arc::clone(self);
327        async move { sr.read_string(id).await }
328            .run_in_task_if(in_task, || "secrets_reader_read".to_string())
329            .await
330    }
331}
332
333/// Extra context to pass through when instantiating a connection for a source
334/// or sink.
335///
336/// Should be kept cheaply cloneable.
337#[derive(Debug, Clone)]
338pub struct ConnectionContext {
339    /// An opaque identifier for the environment in which this process is
340    /// running.
341    ///
342    /// The storage layer is intentionally unaware of the structure within this
343    /// identifier. Higher layers of the stack can make use of that structure,
344    /// but the storage layer should be oblivious to it.
345    pub environment_id: String,
346    /// The level for librdkafka's logs.
347    pub librdkafka_log_level: tracing::Level,
348    /// A prefix for an external ID to use for all AWS AssumeRole operations.
349    pub aws_external_id_prefix: Option<AwsExternalIdPrefix>,
350    /// The ARN for a Materialize-controlled role to assume before assuming
351    /// a customer's requested role for an AWS connection.
352    pub aws_connection_role_arn: Option<String>,
353    /// A secrets reader.
354    pub secrets_reader: Arc<dyn SecretsReader>,
355    /// A cloud resource reader, if supported in this configuration.
356    pub cloud_resource_reader: Option<Arc<dyn CloudResourceReader>>,
357    /// A manager for SSH tunnels.
358    pub ssh_tunnel_manager: SshTunnelManager,
359    /// Cached credentials for `AssumeRole` AWS connections, shared by every
360    /// user of this context in the process.
361    pub aws_credentials_cache: AwsCredentialsCache,
362}
363
364impl ConnectionContext {
365    /// Constructs a new connection context from command line arguments.
366    ///
367    /// **WARNING:** it is critical for security that the `aws_external_id` be
368    /// provided by the operator of the Materialize service (i.e., via a CLI
369    /// argument or environment variable) and not the end user of Materialize
370    /// (e.g., via a configuration option in a SQL statement). See
371    /// [`AwsExternalIdPrefix`] for details.
372    pub fn from_cli_args(
373        environment_id: String,
374        startup_log_level: &CloneableEnvFilter,
375        aws_external_id_prefix: Option<AwsExternalIdPrefix>,
376        aws_connection_role_arn: Option<String>,
377        secrets_reader: Arc<dyn SecretsReader>,
378        cloud_resource_reader: Option<Arc<dyn CloudResourceReader>>,
379    ) -> ConnectionContext {
380        ConnectionContext {
381            environment_id,
382            librdkafka_log_level: mz_ore::tracing::crate_level(
383                &startup_log_level.clone().into(),
384                "librdkafka",
385            ),
386            aws_external_id_prefix,
387            aws_connection_role_arn,
388            secrets_reader,
389            cloud_resource_reader,
390            ssh_tunnel_manager: SshTunnelManager::default(),
391            aws_credentials_cache: AwsCredentialsCache::default(),
392        }
393    }
394
395    /// Constructs a new connection context for usage in tests.
396    pub fn for_tests(secrets_reader: Arc<dyn SecretsReader>) -> ConnectionContext {
397        ConnectionContext {
398            environment_id: "test-environment-id".into(),
399            librdkafka_log_level: tracing::Level::INFO,
400            aws_external_id_prefix: Some(
401                AwsExternalIdPrefix::new_from_cli_argument_or_environment_variable(
402                    "test-aws-external-id-prefix",
403                )
404                .expect("infallible"),
405            ),
406            aws_connection_role_arn: Some(
407                "arn:aws:iam::123456789000:role/MaterializeConnection".into(),
408            ),
409            secrets_reader,
410            cloud_resource_reader: None,
411            ssh_tunnel_manager: SshTunnelManager::default(),
412            aws_credentials_cache: AwsCredentialsCache::default(),
413        }
414    }
415}
416
417#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
418pub enum Connection<C: ConnectionAccess = InlinedConnection> {
419    Kafka(KafkaConnection<C>),
420    Csr(CsrConnection<C>),
421    GlueSchemaRegistry(GlueSchemaRegistryConnection<C>),
422    Postgres(PostgresConnection<C>),
423    Ssh(SshConnection),
424    Aws(AwsConnection),
425    AwsPrivatelink(AwsPrivatelinkConnection),
426    Gcp(gcp::GcpConnection),
427    MySql(MySqlConnection<C>),
428    SqlServer(SqlServerConnectionDetails<C>),
429    IcebergCatalog(IcebergCatalogConnection<C>),
430}
431
432impl<R: ConnectionResolver> IntoInlineConnection<Connection, R>
433    for Connection<ReferencedConnection>
434{
435    fn into_inline_connection(self, r: R) -> Connection {
436        match self {
437            Connection::Kafka(kafka) => Connection::Kafka(kafka.into_inline_connection(r)),
438            Connection::Csr(csr) => Connection::Csr(csr.into_inline_connection(r)),
439            Connection::GlueSchemaRegistry(glue) => {
440                Connection::GlueSchemaRegistry(glue.into_inline_connection(r))
441            }
442            Connection::Postgres(pg) => Connection::Postgres(pg.into_inline_connection(r)),
443            Connection::Ssh(ssh) => Connection::Ssh(ssh),
444            Connection::Aws(aws) => Connection::Aws(aws),
445            Connection::AwsPrivatelink(awspl) => Connection::AwsPrivatelink(awspl),
446            Connection::Gcp(gcp) => Connection::Gcp(gcp),
447            Connection::MySql(mysql) => Connection::MySql(mysql.into_inline_connection(r)),
448            Connection::SqlServer(sql_server) => {
449                Connection::SqlServer(sql_server.into_inline_connection(r))
450            }
451            Connection::IcebergCatalog(iceberg) => {
452                Connection::IcebergCatalog(iceberg.into_inline_connection(r))
453            }
454        }
455    }
456}
457
458impl<C: ConnectionAccess> Connection<C> {
459    /// Whether this connection should be validated by default on creation.
460    pub fn validate_by_default(&self) -> bool {
461        match self {
462            Connection::Kafka(conn) => conn.validate_by_default(),
463            Connection::Csr(conn) => conn.validate_by_default(),
464            Connection::GlueSchemaRegistry(conn) => conn.validate_by_default(),
465            Connection::Postgres(conn) => conn.validate_by_default(),
466            Connection::Ssh(conn) => conn.validate_by_default(),
467            Connection::Aws(conn) => conn.validate_by_default(),
468            Connection::AwsPrivatelink(conn) => conn.validate_by_default(),
469            Connection::Gcp(conn) => conn.validate_by_default(),
470            Connection::MySql(conn) => conn.validate_by_default(),
471            Connection::SqlServer(conn) => conn.validate_by_default(),
472            Connection::IcebergCatalog(conn) => conn.validate_by_default(),
473        }
474    }
475}
476
477impl Connection<InlinedConnection> {
478    /// Validates this connection by attempting to connect to the upstream system.
479    pub async fn validate(
480        &self,
481        id: CatalogItemId,
482        storage_configuration: &StorageConfiguration,
483    ) -> Result<(), ConnectionValidationError> {
484        match self {
485            Connection::Kafka(conn) => conn.validate(id, storage_configuration).await?,
486            Connection::Csr(conn) => conn.validate(id, storage_configuration).await?,
487            Connection::GlueSchemaRegistry(conn) => {
488                conn.validate(id, storage_configuration).await?
489            }
490            Connection::Postgres(conn) => {
491                conn.validate(id, storage_configuration).await?;
492            }
493            Connection::Ssh(conn) => conn.validate(id, storage_configuration).await?,
494            Connection::Aws(conn) => conn.validate(id, storage_configuration).await?,
495            Connection::AwsPrivatelink(conn) => conn.validate(id, storage_configuration).await?,
496            Connection::Gcp(conn) => conn.validate(id, storage_configuration).await?,
497            Connection::MySql(conn) => {
498                conn.validate(id, storage_configuration).await?;
499            }
500            Connection::SqlServer(conn) => {
501                conn.validate(id, storage_configuration).await?;
502            }
503            Connection::IcebergCatalog(conn) => conn.validate(id, storage_configuration).await?,
504        }
505        Ok(())
506    }
507
508    pub fn unwrap_kafka(self) -> <InlinedConnection as ConnectionAccess>::Kafka {
509        match self {
510            Self::Kafka(conn) => conn,
511            o => unreachable!("{o:?} is not a Kafka connection"),
512        }
513    }
514
515    pub fn unwrap_pg(self) -> <InlinedConnection as ConnectionAccess>::Pg {
516        match self {
517            Self::Postgres(conn) => conn,
518            o => unreachable!("{o:?} is not a Postgres connection"),
519        }
520    }
521
522    pub fn unwrap_mysql(self) -> <InlinedConnection as ConnectionAccess>::MySql {
523        match self {
524            Self::MySql(conn) => conn,
525            o => unreachable!("{o:?} is not a MySQL connection"),
526        }
527    }
528
529    pub fn unwrap_sql_server(self) -> <InlinedConnection as ConnectionAccess>::SqlServer {
530        match self {
531            Self::SqlServer(conn) => conn,
532            o => unreachable!("{o:?} is not a SQL Server connection"),
533        }
534    }
535
536    pub fn unwrap_aws(self) -> <InlinedConnection as ConnectionAccess>::Aws {
537        match self {
538            Self::Aws(conn) => conn,
539            o => unreachable!("{o:?} is not an AWS connection"),
540        }
541    }
542
543    pub fn unwrap_gcp(self) -> <InlinedConnection as ConnectionAccess>::Gcp {
544        match self {
545            Self::Gcp(conn) => conn,
546            o => unreachable!("{o:?} is not a GCP connection"),
547        }
548    }
549
550    pub fn unwrap_ssh(self) -> <InlinedConnection as ConnectionAccess>::Ssh {
551        match self {
552            Self::Ssh(conn) => conn,
553            o => unreachable!("{o:?} is not an SSH connection"),
554        }
555    }
556
557    pub fn unwrap_csr(self) -> <InlinedConnection as ConnectionAccess>::Csr {
558        match self {
559            Self::Csr(conn) => conn,
560            o => unreachable!("{o:?} is not a Kafka connection"),
561        }
562    }
563
564    pub fn unwrap_glue_schema_registry(
565        self,
566    ) -> <InlinedConnection as ConnectionAccess>::GlueSchemaRegistry {
567        match self {
568            Self::GlueSchemaRegistry(conn) => conn,
569            o => unreachable!("{o:?} is not an AWS Glue Schema Registry connection"),
570        }
571    }
572
573    pub fn unwrap_iceberg_catalog(self) -> <InlinedConnection as ConnectionAccess>::IcebergCatalog {
574        match self {
575            Self::IcebergCatalog(conn) => conn,
576            o => unreachable!("{o:?} is not an Iceberg catalog connection"),
577        }
578    }
579}
580
581/// An error returned by [`Connection::validate`].
582#[derive(thiserror::Error, Debug)]
583pub enum ConnectionValidationError {
584    #[error(transparent)]
585    Postgres(#[from] PostgresConnectionValidationError),
586    #[error(transparent)]
587    MySql(#[from] MySqlConnectionValidationError),
588    #[error(transparent)]
589    SqlServer(#[from] SqlServerConnectionValidationError),
590    #[error(transparent)]
591    Aws(#[from] AwsConnectionValidationError),
592    #[error(transparent)]
593    Gcp(#[from] gcp::GcpConnectionValidationError),
594    #[error(transparent)]
595    AwsPrivatelinkServiceName(#[from] InvalidAwsPrivatelinkServiceName),
596    #[error("{}", .0.display_with_causes())]
597    Other(#[from] anyhow::Error),
598}
599
600impl ConnectionValidationError {
601    /// Reports additional details about the error, if any are available.
602    pub fn detail(&self) -> Option<String> {
603        match self {
604            ConnectionValidationError::Postgres(e) => e.detail(),
605            ConnectionValidationError::MySql(e) => e.detail(),
606            ConnectionValidationError::SqlServer(e) => e.detail(),
607            ConnectionValidationError::Aws(e) => e.detail(),
608            ConnectionValidationError::Gcp(e) => e.detail(),
609            ConnectionValidationError::AwsPrivatelinkServiceName(_) => None,
610            ConnectionValidationError::Other(_) => None,
611        }
612    }
613
614    /// Reports a hint for the user about how the error could be fixed.
615    pub fn hint(&self) -> Option<String> {
616        match self {
617            ConnectionValidationError::Postgres(e) => e.hint(),
618            ConnectionValidationError::MySql(e) => e.hint(),
619            ConnectionValidationError::SqlServer(e) => e.hint(),
620            ConnectionValidationError::Aws(e) => e.hint(),
621            ConnectionValidationError::Gcp(e) => e.hint(),
622            ConnectionValidationError::AwsPrivatelinkServiceName(e) => Some(e.hint()),
623            ConnectionValidationError::Other(_) => None,
624        }
625    }
626}
627
628impl<C: ConnectionAccess> AlterCompatible for Connection<C> {
629    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
630        match (self, other) {
631            (Self::Aws(s), Self::Aws(o)) => s.alter_compatible(id, o),
632            (Self::AwsPrivatelink(s), Self::AwsPrivatelink(o)) => s.alter_compatible(id, o),
633            (Self::Gcp(s), Self::Gcp(o)) => s.alter_compatible(id, o),
634            (Self::Ssh(s), Self::Ssh(o)) => s.alter_compatible(id, o),
635            (Self::Csr(s), Self::Csr(o)) => s.alter_compatible(id, o),
636            (Self::Kafka(s), Self::Kafka(o)) => s.alter_compatible(id, o),
637            (Self::Postgres(s), Self::Postgres(o)) => s.alter_compatible(id, o),
638            (Self::MySql(s), Self::MySql(o)) => s.alter_compatible(id, o),
639            (Self::SqlServer(s), Self::SqlServer(o)) => s.alter_compatible(id, o),
640            (Self::GlueSchemaRegistry(s), Self::GlueSchemaRegistry(o)) => s.alter_compatible(id, o),
641            (Self::IcebergCatalog(s), Self::IcebergCatalog(o)) => s.alter_compatible(id, o),
642            _ => {
643                tracing::warn!(
644                    "Connection incompatible:\nself:\n{:#?}\n\nother\n{:#?}",
645                    self,
646                    other
647                );
648                Err(AlterError { id })
649            }
650        }
651    }
652}
653
654/// Auth mechanism for Iceberg REST catalogs.
655#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
656pub enum IcebergCatalogAuth<C: ConnectionAccess = InlinedConnection> {
657    /// Use Iceberg catalog REST API's standard OAuth flow.
658    OAuth {
659        /// client_id:client_secret
660        credential: StringOrSecret,
661        /// OAuth2 scope
662        scope: Option<String>,
663        /// Where to exchange `credential` for a bearer token.
664        ///
665        /// `None` uses the endpoint the Iceberg REST specification defines relative to the
666        /// catalog URL, `<url>/v1/oauth/tokens`. Catalogs that host their token endpoint
667        /// elsewhere, or behind an auth gateway that will not serve an unauthenticated
668        /// exchange, need this override.
669        server_url: Option<String>,
670    },
671    Gcp(GcpConnectionReference<C>),
672}
673
674#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
675pub struct RestIcebergCatalog<C: ConnectionAccess = InlinedConnection> {
676    pub auth: IcebergCatalogAuth<C>,
677    /// The warehouse for REST catalogs
678    pub warehouse: Option<String>,
679    /// Which form of storage-access delegation to request from the catalog, if any.
680    ///
681    /// `None` means "do not request storage-access delegation".
682    /// If we do not have permission to request delegated access but request it anyway,
683    /// a catalog can reject our whole request,
684    /// even if we have our own storage credentials to fall back on.
685    pub access_delegation: Option<IcebergAccessDelegation>,
686    /// Which object store the catalog's tables live in.
687    ///
688    /// Defaults to S3. A REST catalog does not tell us this, so a table backed
689    /// by GCS or ADLS is unreadable until the connection says so.
690    pub storage_provider: IcebergStorageProvider,
691}
692
693/// The value Materialize sends in the Iceberg REST `X-Iceberg-Access-Delegation`
694/// header, naming how the catalog should grant access to table storage.
695#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
696pub enum IcebergAccessDelegation {
697    /// Ask the catalog to mint temporary, table-scoped storage credentials.
698    VendedCredentials,
699}
700
701impl IcebergAccessDelegation {
702    /// The header value, as spelled in the Iceberg REST specification.
703    pub fn as_header_value(&self) -> &'static str {
704        match self {
705            IcebergAccessDelegation::VendedCredentials => "vended-credentials",
706        }
707    }
708}
709
710impl<C: ConnectionAccess> AlterCompatible for RestIcebergCatalog<C> {
711    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
712        // Auth and access delegation are not considered for compatibility, because they can
713        // be changed without breaking existing tables.
714        if (self.warehouse != other.warehouse) || (self.storage_provider != other.storage_provider)
715        {
716            tracing::warn!(
717                "RestIcebergCatalog incompatible:\nself:\n{:#?}\n\nother\n{:#?}",
718                self,
719                other
720            );
721            Err(AlterError { id })
722        } else {
723            Ok(())
724        }
725    }
726}
727
728#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
729pub struct S3TablesRestIcebergCatalog<C: ConnectionAccess = InlinedConnection> {
730    /// The AWS connection details, for s3tables
731    pub aws_connection: AwsConnectionReference<C>,
732    /// The warehouse for s3tables
733    pub warehouse: String,
734}
735
736impl<R: ConnectionResolver> IntoInlineConnection<IcebergCatalogAuth, R>
737    for IcebergCatalogAuth<ReferencedConnection>
738{
739    fn into_inline_connection(self, r: R) -> IcebergCatalogAuth {
740        match self {
741            IcebergCatalogAuth::Gcp(x) => IcebergCatalogAuth::Gcp(x.into_inline_connection(&r)),
742            IcebergCatalogAuth::OAuth {
743                credential,
744                scope,
745                server_url,
746            } => IcebergCatalogAuth::OAuth {
747                credential,
748                scope,
749                server_url,
750            },
751        }
752    }
753}
754
755impl<R: ConnectionResolver> IntoInlineConnection<RestIcebergCatalog, R>
756    for RestIcebergCatalog<ReferencedConnection>
757{
758    fn into_inline_connection(self, r: R) -> RestIcebergCatalog {
759        RestIcebergCatalog {
760            auth: self.auth.into_inline_connection(&r),
761            warehouse: self.warehouse,
762            access_delegation: self.access_delegation,
763            storage_provider: self.storage_provider,
764        }
765    }
766}
767
768impl<R: ConnectionResolver> IntoInlineConnection<S3TablesRestIcebergCatalog, R>
769    for S3TablesRestIcebergCatalog<ReferencedConnection>
770{
771    fn into_inline_connection(self, r: R) -> S3TablesRestIcebergCatalog {
772        S3TablesRestIcebergCatalog {
773            aws_connection: self.aws_connection.into_inline_connection(&r),
774            warehouse: self.warehouse,
775        }
776    }
777}
778
779impl<C: ConnectionAccess> AlterCompatible for S3TablesRestIcebergCatalog<C> {
780    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
781        if self.aws_connection.connection_id != other.aws_connection.connection_id
782            || self.warehouse != other.warehouse
783        {
784            tracing::warn!(
785                "S3TablesRestIcebergCatalog incompatible:\nself:\n{:#?}\n\nother\n{:#?}",
786                self,
787                other
788            );
789            Err(AlterError { id })
790        } else {
791            self.aws_connection
792                .connection
793                .alter_compatible(id, &other.aws_connection.connection)?;
794            Ok(())
795        }
796    }
797}
798
799#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
800pub enum IcebergCatalogType {
801    Rest,
802    S3TablesRest,
803}
804
805/// Which object store holds the data files of a REST catalog's tables.
806///
807/// The catalog protocol says nothing about this: a REST catalog hands back
808/// storage locations and credentials, and the client has to already know how to
809/// talk to that store. So it is configured per connection rather than
810/// discovered.
811#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
812pub enum IcebergStorageProvider {
813    S3,
814    Gcs,
815    Adls,
816}
817
818impl IcebergStorageProvider {
819    /// The name as spelled in SQL.
820    pub fn as_str(&self) -> &'static str {
821        match self {
822            IcebergStorageProvider::S3 => "s3",
823            IcebergStorageProvider::Gcs => "gcs",
824            IcebergStorageProvider::Adls => "adls",
825        }
826    }
827}
828
829impl Default for IcebergStorageProvider {
830    fn default() -> Self {
831        IcebergStorageProvider::S3
832    }
833}
834
835#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
836pub enum IcebergCatalogImpl<C: ConnectionAccess = InlinedConnection> {
837    Rest(RestIcebergCatalog<C>),
838    S3TablesRest(S3TablesRestIcebergCatalog<C>),
839}
840
841impl<R: ConnectionResolver> IntoInlineConnection<IcebergCatalogImpl, R>
842    for IcebergCatalogImpl<ReferencedConnection>
843{
844    fn into_inline_connection(self, r: R) -> IcebergCatalogImpl {
845        match self {
846            IcebergCatalogImpl::Rest(rest) => {
847                IcebergCatalogImpl::Rest(rest.into_inline_connection(r))
848            }
849            IcebergCatalogImpl::S3TablesRest(s3tables) => {
850                IcebergCatalogImpl::S3TablesRest(s3tables.into_inline_connection(r))
851            }
852        }
853    }
854}
855
856impl<C: ConnectionAccess> AlterCompatible for IcebergCatalogImpl<C> {
857    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
858        match (self, other) {
859            (IcebergCatalogImpl::Rest(rest), IcebergCatalogImpl::Rest(other_rest)) => {
860                rest.alter_compatible(id, other_rest)
861            }
862            (
863                IcebergCatalogImpl::S3TablesRest(s3tables),
864                IcebergCatalogImpl::S3TablesRest(other_s3tables),
865            ) => s3tables.alter_compatible(id, other_s3tables),
866            _ => Err(AlterError { id }),
867        }
868    }
869}
870
871#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
872pub struct IcebergCatalogConnection<C: ConnectionAccess = InlinedConnection> {
873    /// The catalog impl impl of that catalog
874    pub catalog: IcebergCatalogImpl<C>,
875    /// Where the catalog is located
876    pub uri: reqwest_0_12::Url,
877}
878
879impl<C: ConnectionAccess> AlterCompatible for IcebergCatalogConnection<C> {
880    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
881        let compatibility_checks = [
882            (
883                self.catalog.alter_compatible(id, &other.catalog).is_ok(),
884                "catalog",
885            ),
886            (self.uri == other.uri, "uri"),
887        ];
888        for (is_ok, field) in compatibility_checks {
889            if !is_ok {
890                tracing::warn!(
891                    "IcebergCatalogConnection incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
892                    self,
893                    other
894                );
895                return Err(AlterError { id });
896            }
897        }
898        Ok(())
899    }
900}
901
902impl<R: ConnectionResolver> IntoInlineConnection<IcebergCatalogConnection, R>
903    for IcebergCatalogConnection<ReferencedConnection>
904{
905    fn into_inline_connection(self, r: R) -> IcebergCatalogConnection {
906        IcebergCatalogConnection {
907            catalog: self.catalog.into_inline_connection(&r),
908            uri: self.uri,
909        }
910    }
911}
912
913impl<C: ConnectionAccess> IcebergCatalogConnection<C> {
914    fn validate_by_default(&self) -> bool {
915        true
916    }
917}
918
919impl IcebergCatalogConnection<InlinedConnection> {
920    /// Connects to the catalog.
921    ///
922    /// `table` names the table this handle will be used against. It is needed only to keep
923    /// catalog-vended storage credentials refreshed, which the REST specification scopes to a
924    /// single table. Passing `None` leaves the connection on whatever credentials the catalog
925    /// supplies at `loadTable` time, which expire.
926    pub async fn connect(
927        &self,
928        storage_configuration: &StorageConfiguration,
929        in_task: InTask,
930        table: Option<&TableIdent>,
931    ) -> Result<Arc<dyn Catalog>, anyhow::Error> {
932        match self.catalog {
933            IcebergCatalogImpl::S3TablesRest(ref s3tables) => {
934                // S3 Tables signs every request with SigV4 off a refreshable AWS provider, so it
935                // has no vended credential to keep alive.
936                self.connect_s3tables(s3tables, storage_configuration, in_task)
937                    .await
938            }
939            IcebergCatalogImpl::Rest(ref rest) => {
940                self.connect_rest(rest, storage_configuration, in_task, table)
941                    .await
942            }
943        }
944    }
945
946    pub fn catalog_type(&self) -> IcebergCatalogType {
947        match self.catalog {
948            IcebergCatalogImpl::S3TablesRest(_) => IcebergCatalogType::S3TablesRest,
949            IcebergCatalogImpl::Rest(_) => IcebergCatalogType::Rest,
950        }
951    }
952
953    pub fn s3tables_catalog(&self) -> Option<&S3TablesRestIcebergCatalog> {
954        match &self.catalog {
955            IcebergCatalogImpl::S3TablesRest(s3tables) => Some(s3tables),
956            IcebergCatalogImpl::Rest(_) => None,
957        }
958    }
959
960    pub fn rest_catalog(&self) -> Option<&RestIcebergCatalog> {
961        match &self.catalog {
962            IcebergCatalogImpl::Rest(rest) => Some(rest),
963            IcebergCatalogImpl::S3TablesRest(_) => None,
964        }
965    }
966
967    async fn connect_s3tables(
968        &self,
969        s3tables: &S3TablesRestIcebergCatalog,
970        storage_configuration: &StorageConfiguration,
971        in_task: InTask,
972    ) -> Result<Arc<dyn Catalog>, anyhow::Error> {
973        let secret_reader = &storage_configuration.connection_context.secrets_reader;
974        let aws_ref = &s3tables.aws_connection;
975
976        let aws_region = aws_ref
977            .connection
978            .region
979            .clone()
980            .unwrap_or_else(|| "us-east-1".to_string());
981
982        let mut props = vec![
983            (S3_REGION.to_string(), aws_region.clone()),
984            (S3_DISABLE_EC2_METADATA.to_string(), "true".to_string()),
985            (
986                REST_CATALOG_PROP_WAREHOUSE.to_string(),
987                s3tables.warehouse.clone(),
988            ),
989            (REST_CATALOG_PROP_URI.to_string(), self.uri.to_string()),
990        ];
991
992        let aws_auth = aws_ref.connection.auth.clone();
993
994        if let AwsAuth::Credentials(creds) = &aws_auth {
995            props.push((
996                S3_ACCESS_KEY_ID.to_string(),
997                creds
998                    .access_key_id
999                    .get_string(in_task, secret_reader)
1000                    .await?,
1001            ));
1002            props.push((
1003                S3_SECRET_ACCESS_KEY.to_string(),
1004                secret_reader.read_string(creds.secret_access_key).await?,
1005            ));
1006        }
1007
1008        // Sign REST catalog requests with the Materialize AWS credential chain
1009        // via a custom `RequestAuthenticator`. For AssumeRole auth, also feed
1010        // the chain to OpenDAL's S3 loader so data-file IO uses the same creds.
1011        //
1012        // For AssumeRole auth, the provider serves cached credentials that a
1013        // background task keeps fresh, so no request through this catalog ever
1014        // waits on STS. The task lives as long as the catalog holds the
1015        // provider.
1016        let credentials_provider = match &aws_auth {
1017            // NOTE: This branch never contacts the connection's ENDPOINT.
1018            // REST requests go to the catalog URI and the STS calls use the
1019            // SDK defaults. The endpoint is still validated so a forbidden
1020            // one is rejected rather than silently ignored.
1021            AwsAuth::AssumeRole(assume_role) => {
1022                aws_ref.connection.validate_endpoint(
1023                    ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
1024                )?;
1025                assume_role
1026                    .prefetch_credentials(
1027                        &storage_configuration.connection_context,
1028                        aws_ref.connection_id,
1029                        storage_configuration.config_set(),
1030                        format!("aws-connection-{}", aws_ref.connection_id),
1031                    )
1032                    .await
1033                    .with_context(|| {
1034                        format!(
1035                            "failed to initialize AssumeRole credentials for S3 Tables Iceberg \
1036                             catalog (catalog uri: {}, warehouse: {})",
1037                            self.uri, s3tables.warehouse
1038                        )
1039                    })?
1040            }
1041            AwsAuth::Credentials(_) => {
1042                let aws_config = aws_ref
1043                    .connection
1044                    .load_sdk_config(
1045                        &storage_configuration.connection_context,
1046                        aws_ref.connection_id,
1047                        in_task,
1048                        ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
1049                    )
1050                    .await
1051                    .with_context(|| {
1052                        format!(
1053                            "failed to load AWS SDK config for S3 Tables Iceberg catalog \
1054                             (connection id: {}, auth method: {}, catalog uri: {}, warehouse: {})",
1055                            aws_ref.connection_id,
1056                            aws_ref.connection.auth_method(),
1057                            self.uri,
1058                            s3tables.warehouse
1059                        )
1060                    })?;
1061                aws_config
1062                    .credentials_provider()
1063                    .ok_or_else(|| anyhow!("aws_config missing credentials provider"))?
1064            }
1065        };
1066
1067        let authenticator = Arc::new(Sigv4Authenticator {
1068            provider: credentials_provider.clone(),
1069            region: aws_region.clone(),
1070            signing_name: "s3tables".to_string(),
1071        });
1072
1073        // N.B. We're using the AWS credentials from the catalog connection for the storage layer
1074        //   even though the sink comes with its own (unused) AWS credentials for storage.
1075        let customized_credential_load = if matches!(aws_auth, AwsAuth::AssumeRole(_)) {
1076            Some(CustomAwsCredentialLoader::new(AwsSdkCredentialLoader::new(
1077                credentials_provider,
1078            )))
1079        } else {
1080            None
1081        };
1082
1083        let storage_factory = Arc::new(OpenDalStorageFactory::S3 {
1084            customized_credential_load,
1085        });
1086
1087        let catalog = RestCatalogBuilder::default()
1088            .with_storage_factory(storage_factory)
1089            .with_authenticator(authenticator)
1090            .load("IcebergCatalog", props.into_iter().collect())
1091            .await
1092            .with_context(|| {
1093                format!(
1094                    "failed to create S3 Tables Iceberg catalog \
1095                     (connection id: {}, catalog uri: {}, warehouse: {})",
1096                    aws_ref.connection_id, self.uri, s3tables.warehouse
1097                )
1098            })?;
1099
1100        Ok(Arc::new(catalog))
1101    }
1102
1103    /// Collects the headers `iceberg-rust` puts on every catalog request out of the `header.*`
1104    /// props it takes them from.
1105    ///
1106    /// The credential endpoints Materialize calls directly bypass the catalog client, so without
1107    /// this they would reach the same server missing headers it may require, `x-goog-user-project`
1108    /// on a GCP-hosted catalog among them.
1109    fn catalog_headers(props: &BTreeMap<String, String>) -> Result<HeaderMap, anyhow::Error> {
1110        props
1111            .iter()
1112            .filter_map(|(k, v)| {
1113                k.strip_prefix(REST_CATALOG_HEADER_PROP_PREFIX)
1114                    .map(|name| (name, v))
1115            })
1116            .map(|(name, value)| {
1117                let name = HeaderName::try_from(name)
1118                    .with_context(|| format!("invalid Iceberg catalog header name: {name}"))?;
1119                let value = HeaderValue::try_from(value)
1120                    .with_context(|| format!("invalid Iceberg catalog header value for {name}"))?;
1121                Ok((name, value))
1122            })
1123            .collect()
1124    }
1125
1126    /// Resolves the endpoint that vends storage credentials for `table`, or `None` if this
1127    /// connection has no use for one.
1128    ///
1129    /// A loader built on the returned endpoint takes sole responsibility for storage credentials,
1130    /// so `None` is the signal to leave the catalog's static `storage-credentials` props in force.
1131    /// It means either that the connection did not ask for delegation, or that the caller named no
1132    /// table, and the specification scopes vended credentials to a single table.
1133    async fn vended_credential_endpoint(
1134        &self,
1135        rest: &RestIcebergCatalog,
1136        client: &reqwest_0_12::Client,
1137        token: &Arc<dyn TokenProvider>,
1138        headers: &HeaderMap,
1139        table: Option<&TableIdent>,
1140    ) -> Result<Option<Url>, anyhow::Error> {
1141        match (&rest.access_delegation, table) {
1142            (Some(IcebergAccessDelegation::VendedCredentials), Some(table)) => Ok(Some(
1143                iceberg_credentials::table_credentials_endpoint(
1144                    &self.uri,
1145                    client,
1146                    token,
1147                    headers,
1148                    rest.warehouse.as_deref(),
1149                    table,
1150                )
1151                .await?,
1152            )),
1153            _ => Ok(None),
1154        }
1155    }
1156
1157    /// Builds a GCS storage factory, refreshing vended credentials from `endpoint` if there is one.
1158    fn gcs_storage_factory(
1159        endpoint: Option<Url>,
1160        client: &reqwest_0_12::Client,
1161        token: &Arc<dyn TokenProvider>,
1162        headers: &HeaderMap,
1163    ) -> OpenDalStorageFactory {
1164        OpenDalStorageFactory::Gcs {
1165            customized_credential_load: endpoint.map(|endpoint| {
1166                CustomGcsCredentialLoader::new(iceberg_credentials::VendedCredentialLoader::new(
1167                    client.clone(),
1168                    endpoint,
1169                    Arc::clone(token),
1170                    headers.clone(),
1171                ))
1172            }),
1173        }
1174    }
1175
1176    async fn connect_rest(
1177        &self,
1178        rest: &RestIcebergCatalog,
1179        storage_configuration: &StorageConfiguration,
1180        in_task: InTask,
1181        table: Option<&TableIdent>,
1182    ) -> Result<Arc<dyn Catalog>, anyhow::Error> {
1183        let mut props = BTreeMap::from([(
1184            REST_CATALOG_PROP_URI.to_string(),
1185            self.uri.to_string().clone(),
1186        )]);
1187
1188        if let Some(warehouse) = &rest.warehouse {
1189            props.insert(REST_CATALOG_PROP_WAREHOUSE.to_string(), warehouse.clone());
1190        }
1191
1192        // One client for catalog requests, OAuth token requests, and credential refreshes, so all
1193        // three share a connection pool. `iceberg-rust` would otherwise default to its own.
1194        let client = reqwest_0_12::Client::new();
1195
1196        // Catalog auth is configured through a combination of `props` and `.with_authenticator(...)`,
1197        // which happen at different stages of the [`RestCatalogBuilder`] -> [`RestCatalog`]
1198        // construction pipeline.
1199        let (storage_factory, custom_authenticator) = match &rest.auth {
1200            IcebergCatalogAuth::OAuth {
1201                credential,
1202                scope,
1203                server_url,
1204            } => {
1205                let credential = credential
1206                    .get_string(
1207                        in_task,
1208                        &storage_configuration.connection_context.secrets_reader,
1209                    )
1210                    .await
1211                    .map_err(|e| anyhow!("failed to read Iceberg catalog credential: {e}"))?;
1212
1213                if let Some(server_url) = server_url {
1214                    // The OAuth2 exchange POSTs the catalog credential to this URL, so a URL
1215                    // aimed inside our own network turns the connection into a request forger
1216                    // against, say, a cloud metadata endpoint. Resolve it and reject private
1217                    // addresses, the same check every other host we dial directly gets.
1218                    //
1219                    // NOTE: the resolved addresses are only checked, not pinned. The catalog
1220                    // client offers no hook to dial a pre-resolved address, so a name that
1221                    // resolves differently between this check and the request slips through.
1222                    // Kafka and Confluent Schema Registry connections do pin theirs.
1223                    let url = Url::parse(server_url).with_context(|| {
1224                        format!("invalid OAUTH2 SERVER URL for Iceberg catalog: {server_url}")
1225                    })?;
1226                    let host = url.host_str().ok_or_else(|| {
1227                        anyhow!("OAUTH2 SERVER URL for Iceberg catalog has no host: {server_url}")
1228                    })?;
1229                    resolve_address(
1230                        host,
1231                        ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
1232                    )
1233                    .await
1234                    .with_context(|| {
1235                        format!("OAUTH2 SERVER URL for Iceberg catalog is not resolvable to an external address: {server_url}")
1236                    })?;
1237
1238                    props.insert(
1239                        REST_CATALOG_PROP_OAUTH2_SERVER_URI.to_string(),
1240                        server_url.clone(),
1241                    );
1242                }
1243
1244                // Materialize builds an OAuth2 provider shared across both catalog requests
1245                // and the vended credentials refresh below.
1246                let token_endpoint = match server_url {
1247                    Some(server_url) => server_url.clone(),
1248                    // Matches `iceberg-rust`'s default when no `oauth2-server-uri` is configured.
1249                    None => format!(
1250                        "{}/v1/oauth/tokens",
1251                        self.uri.as_str().trim_end_matches('/')
1252                    ),
1253                };
1254                let (client_id, client_secret) = match credential.split_once(':') {
1255                    Some((client_id, client_secret)) => {
1256                        (Some(client_id.to_string()), client_secret.to_string())
1257                    }
1258                    None => (None, credential),
1259                };
1260                let oauth_params = BTreeMap::from([(
1261                    OAUTH2_PARAM_SCOPE.to_string(),
1262                    // The default `iceberg-rust` applies when the connection names no scope.
1263                    scope.clone().unwrap_or_else(|| "catalog".to_string()),
1264                )]);
1265                let token: Arc<dyn TokenProvider> = Arc::new(OAuth2TokenProvider::new(
1266                    client.clone(),
1267                    client_id,
1268                    client_secret,
1269                    token_endpoint,
1270                    // The token request needs none of the catalog's headers, and
1271                    // `OAuth2TokenProvider` sets the form content type itself.
1272                    HeaderMap::new(),
1273                    oauth_params.into_iter().collect(),
1274                ));
1275
1276                let headers = Self::catalog_headers(&props)?;
1277                let endpoint = self
1278                    .vended_credential_endpoint(rest, &client, &token, &headers, table)
1279                    .await?;
1280
1281                (
1282                    // The catalog tells us where the data lives but not what
1283                    // kind of store it is, so the connection has to say.
1284                    match rest.storage_provider {
1285                        // When used with MinIO, Polaris returns a config with:
1286                        //   s3.access-key-id, s3.secret-access-key, s3.endpoint, ...
1287                        // `iceberg-rust` forwards these props to `opendal`. When the catalog
1288                        // vends instead, it returns per-table `storage-credentials` that
1289                        // `iceberg-rust` wires into the same FileIO.
1290                        // N.B. This is not confirmed to work with other catalog & storage implementations.
1291                        IcebergStorageProvider::S3 => OpenDalStorageFactory::S3 {
1292                            customized_credential_load: endpoint.map(|endpoint| {
1293                                CustomAwsCredentialLoader::new(
1294                                    iceberg_credentials::VendedCredentialLoader::new(
1295                                        client.clone(),
1296                                        endpoint,
1297                                        Arc::clone(&token),
1298                                        headers.clone(),
1299                                    ),
1300                                )
1301                            }),
1302                        },
1303                        IcebergStorageProvider::Gcs => {
1304                            Self::gcs_storage_factory(endpoint, &client, &token, &headers)
1305                        }
1306                        IcebergStorageProvider::Adls => OpenDalStorageFactory::Azdls {
1307                            customized_credential_load: endpoint.map(|endpoint| {
1308                                CustomAzdlsCredentialLoader::new(
1309                                    iceberg_credentials::VendedCredentialLoader::new(
1310                                        client.clone(),
1311                                        endpoint,
1312                                        Arc::clone(&token),
1313                                        headers.clone(),
1314                                    ),
1315                                )
1316                            }),
1317                        },
1318                    },
1319                    // NOTE: We construct our own OAuth authenticator for the Catalog client instead of using the one built in.
1320                    // This means we ignore auth overrides from `/v1/config` (e.g. `oauth2-server-uri`).
1321                    // This is okay because users can set these configs from Mz SQL.
1322                    Some(iceberg_catalog_rest::BearerTokenAuthenticator::new(token)),
1323                )
1324            }
1325            IcebergCatalogAuth::Gcp(gcp_connection_reference) => {
1326                let (creds_json, service_account) = gcp_connection_reference
1327                    .connection
1328                    .read_credentials(storage_configuration)
1329                    .await
1330                    .map_err(|e| anyhow!("failed to parse GCP service account JSON: {e}"))?;
1331
1332                props.insert(
1333                    GCS_CREDENTIALS_JSON.to_owned(),
1334                    base64::engine::general_purpose::STANDARD.encode(creds_json),
1335                );
1336                // We supplied a service account key. Don't look elsewhere for GCP credentials.
1337                props.insert(GCS_DISABLE_VM_METADATA.to_owned(), "true".to_owned());
1338                props.insert(GCS_DISABLE_CONFIG_LOAD.to_owned(), "true".to_owned());
1339                if let Some(project_id) = service_account.project_id() {
1340                    props.insert(GCS_USER_PROJECT.to_owned(), project_id.to_owned());
1341                    props.insert(
1342                        "header.x-goog-user-project".to_owned(),
1343                        project_id.to_owned(),
1344                    );
1345                }
1346
1347                // The service account authenticates catalog requests whether or not the catalog
1348                // vends storage credentials, and doubles as the token source for refreshing them.
1349                let token: Arc<dyn TokenProvider> = Arc::new(GcpTokenProvider { service_account });
1350                let headers = Self::catalog_headers(&props)?;
1351                let endpoint = self
1352                    .vended_credential_endpoint(rest, &client, &token, &headers, table)
1353                    .await?;
1354
1355                (
1356                    // A GCP-hosted catalog vends GCS credentials, so the storage provider is not
1357                    // in question here the way it is for a generic REST catalog.
1358                    //
1359                    // NOTE: with delegation the service account key above stops governing storage
1360                    // and only authenticates the catalog. That is not a change in precedence:
1361                    // OpenDAL already preferred the vended token over a credential file, and a
1362                    // loader only keeps that token from expiring.
1363                    Self::gcs_storage_factory(endpoint, &client, &token, &headers),
1364                    Some(iceberg_catalog_rest::BearerTokenAuthenticator::new(token)),
1365                )
1366            }
1367        };
1368
1369        // Inserted after the storage factory is built, so that the loaders above carry only the
1370        // headers the catalog client would send on an ordinary request. Each adds this one itself,
1371        // since the credentials endpoint is the one request that always asks for delegation.
1372        if let Some(delegation) = &rest.access_delegation {
1373            props.insert(
1374                REST_CATALOG_PROP_ACCESS_DELEGATION.to_string(),
1375                delegation.as_header_value().to_string(),
1376            );
1377        }
1378
1379        let mut catalog = RestCatalogBuilder::default()
1380            .with_storage_factory(Arc::new(storage_factory))
1381            .with_client(client);
1382        if let Some(auth) = custom_authenticator {
1383            catalog = catalog.with_authenticator(Arc::new(auth));
1384        }
1385        let catalog = catalog
1386            .load("IcebergCatalog", props.into_iter().collect())
1387            .await
1388            .map_err(|e| anyhow!("failed to create Iceberg catalog: {e}"))?;
1389        Ok(Arc::new(catalog))
1390    }
1391
1392    async fn validate(
1393        &self,
1394        _id: CatalogItemId,
1395        storage_configuration: &StorageConfiguration,
1396    ) -> Result<(), ConnectionValidationError> {
1397        // Validation only lists namespaces, so it needs no table-scoped credentials.
1398        let catalog = self
1399            .connect(storage_configuration, InTask::No, None)
1400            .await
1401            .map_err(|e| {
1402                ConnectionValidationError::Other(anyhow!("failed to connect to catalog: {e}"))
1403            })?;
1404
1405        // If we can list namespaces, the connection is valid.
1406        catalog.list_namespaces(None).await.map_err(|e| {
1407            ConnectionValidationError::Other(anyhow!("failed to list namespaces: {e}"))
1408        })?;
1409
1410        Ok(())
1411    }
1412}
1413
1414#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
1415pub struct AwsPrivatelinkConnection {
1416    pub service_name: String,
1417    pub availability_zones: Vec<String>,
1418}
1419
1420impl AlterCompatible for AwsPrivatelinkConnection {
1421    fn alter_compatible(&self, _id: GlobalId, _other: &Self) -> Result<(), AlterError> {
1422        // Every element of the AwsPrivatelinkConnection connection is configurable.
1423        Ok(())
1424    }
1425}
1426
1427/// A `SERVICE NAME` that cannot name an AWS VPC endpoint service.
1428#[derive(Clone, Debug, Eq, PartialEq)]
1429pub struct InvalidAwsPrivatelinkServiceName {
1430    pub name: String,
1431}
1432
1433impl fmt::Display for InvalidAwsPrivatelinkServiceName {
1434    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1435        write!(
1436            f,
1437            "invalid AWS PrivateLink service name {}",
1438            self.name.quoted()
1439        )
1440    }
1441}
1442
1443impl std::error::Error for InvalidAwsPrivatelinkServiceName {}
1444
1445impl InvalidAwsPrivatelinkServiceName {
1446    /// Explains how to find the right value.
1447    pub fn hint(&self) -> String {
1448        "SERVICE NAME must name an AWS VPC endpoint service, for example \
1449         `com.amazonaws.vpce.us-east-1.vpce-svc-0e123abc123198abc`. Endpoint service names are \
1450         listed in the AWS console under VPC > Endpoint services."
1451            .into()
1452    }
1453}
1454
1455impl AwsPrivatelinkConnection {
1456    /// Checks that `service_name` could name an AWS VPC endpoint service.
1457    ///
1458    /// Every endpoint service name starts with `com.amazonaws.`, whether the
1459    /// service is customer-owned (`com.amazonaws.vpce.<region>.vpce-svc-<id>`)
1460    /// or AWS-managed (`com.amazonaws.<region>.<service>`). Only the prefix is
1461    /// checked, so a name AWS would accept is never rejected here.
1462    pub fn check_service_name(service_name: &str) -> Result<(), InvalidAwsPrivatelinkServiceName> {
1463        if service_name.starts_with("com.amazonaws.") {
1464            return Ok(());
1465        }
1466        Err(InvalidAwsPrivatelinkServiceName {
1467            name: service_name.to_string(),
1468        })
1469    }
1470}
1471
1472#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
1473pub struct KafkaTlsConfig {
1474    pub identity: Option<TlsIdentity>,
1475    pub root_cert: Option<StringOrSecret>,
1476}
1477
1478#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
1479pub struct KafkaSaslConfig<C: ConnectionAccess = InlinedConnection> {
1480    pub mechanism: String,
1481    pub username: StringOrSecret,
1482    pub password: Option<CatalogItemId>,
1483    pub aws: Option<AwsConnectionReference<C>>,
1484}
1485
1486impl<R: ConnectionResolver> IntoInlineConnection<KafkaSaslConfig, R>
1487    for KafkaSaslConfig<ReferencedConnection>
1488{
1489    fn into_inline_connection(self, r: R) -> KafkaSaslConfig {
1490        KafkaSaslConfig {
1491            mechanism: self.mechanism,
1492            username: self.username,
1493            password: self.password,
1494            aws: self.aws.map(|aws| aws.into_inline_connection(&r)),
1495        }
1496    }
1497}
1498
1499/// Specifies a Kafka broker in a [`KafkaConnection`].
1500#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
1501pub struct KafkaBroker<C: ConnectionAccess = InlinedConnection> {
1502    /// The address of the Kafka broker.
1503    pub address: String,
1504    /// An optional tunnel to use when connecting to the broker.
1505    pub tunnel: Tunnel<C>,
1506}
1507
1508impl<R: ConnectionResolver> IntoInlineConnection<KafkaBroker, R>
1509    for KafkaBroker<ReferencedConnection>
1510{
1511    fn into_inline_connection(self, r: R) -> KafkaBroker {
1512        let KafkaBroker { address, tunnel } = self;
1513        KafkaBroker {
1514            address,
1515            tunnel: tunnel.into_inline_connection(r),
1516        }
1517    }
1518}
1519
1520#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize, Default)]
1521pub struct KafkaTopicOptions {
1522    /// The replication factor for the topic.
1523    /// If `None`, the broker default will be used.
1524    pub replication_factor: Option<NonNeg<i32>>,
1525    /// The number of partitions to create.
1526    /// If `None`, the broker default will be used.
1527    pub partition_count: Option<NonNeg<i32>>,
1528    /// The initial configuration parameters for the topic.
1529    pub topic_config: BTreeMap<String, String>,
1530}
1531
1532#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
1533pub struct KafkaConnection<C: ConnectionAccess = InlinedConnection> {
1534    pub brokers: Vec<KafkaBroker<C>>,
1535    /// A tunnel through which to route traffic,
1536    /// that can be overridden for individual brokers
1537    /// in `brokers`.
1538    pub default_tunnel: Tunnel<C>,
1539    pub progress_topic: Option<String>,
1540    pub progress_topic_options: KafkaTopicOptions,
1541    pub options: BTreeMap<String, StringOrSecret>,
1542    pub tls: Option<KafkaTlsConfig>,
1543    pub sasl: Option<KafkaSaslConfig<C>>,
1544}
1545
1546impl<R: ConnectionResolver> IntoInlineConnection<KafkaConnection, R>
1547    for KafkaConnection<ReferencedConnection>
1548{
1549    fn into_inline_connection(self, r: R) -> KafkaConnection {
1550        let KafkaConnection {
1551            brokers,
1552            progress_topic,
1553            progress_topic_options,
1554            default_tunnel,
1555            options,
1556            tls,
1557            sasl,
1558        } = self;
1559
1560        let brokers = brokers
1561            .into_iter()
1562            .map(|broker| broker.into_inline_connection(&r))
1563            .collect();
1564
1565        KafkaConnection {
1566            brokers,
1567            progress_topic,
1568            progress_topic_options,
1569            default_tunnel: default_tunnel.into_inline_connection(&r),
1570            options,
1571            tls,
1572            sasl: sasl.map(|sasl| sasl.into_inline_connection(&r)),
1573        }
1574    }
1575}
1576
1577impl<C: ConnectionAccess> KafkaConnection<C> {
1578    /// Returns the name of the progress topic to use for the connection.
1579    ///
1580    /// The caller is responsible for providing the connection ID as it is not
1581    /// known to `KafkaConnection`.
1582    ///
1583    /// NOTE: the `mz_catalog.mz_kafka_connections` builtin materialized view
1584    /// reconstructs the default (`_materialize-progress-<env>-<conn>`) in SQL
1585    /// (see `MZ_KAFKA_CONNECTIONS` in `src/catalog/src/builtin/mz_catalog.rs`).
1586    /// Keep the two in sync.
1587    pub fn progress_topic(
1588        &self,
1589        connection_context: &ConnectionContext,
1590        connection_id: CatalogItemId,
1591    ) -> Cow<'_, str> {
1592        if let Some(progress_topic) = &self.progress_topic {
1593            Cow::Borrowed(progress_topic)
1594        } else {
1595            Cow::Owned(format!(
1596                "_materialize-progress-{}-{}",
1597                connection_context.environment_id, connection_id,
1598            ))
1599        }
1600    }
1601
1602    fn validate_by_default(&self) -> bool {
1603        true
1604    }
1605}
1606
1607impl KafkaConnection {
1608    /// Generates a string that can be used as the base for a configuration ID
1609    /// (e.g., `client.id`, `group.id`, `transactional.id`) for a Kafka source
1610    /// or sink.
1611    ///
1612    /// NOTE: the `mz_catalog.mz_kafka_sources` builtin materialized view
1613    /// reconstructs this exact `materialize-<env>-<conn>-<obj>` format in SQL
1614    /// (see `MZ_KAFKA_SOURCES` in `src/catalog/src/builtin/mz_catalog.rs`).
1615    /// The two must stay in sync. `test/testdrive/kafka-commit.td` guards this
1616    /// by feeding the view's reconstructed value into `kafka-verify-commit`,
1617    /// so a divergence here fails that test.
1618    pub fn id_base(
1619        connection_context: &ConnectionContext,
1620        connection_id: CatalogItemId,
1621        object_id: GlobalId,
1622    ) -> String {
1623        format!(
1624            "materialize-{}-{}-{}",
1625            connection_context.environment_id, connection_id, object_id,
1626        )
1627    }
1628
1629    /// Enriches the provided `client_id` according to any enrichment rules in
1630    /// the `kafka_client_id_enrichment_rules` configuration parameter.
1631    pub fn enrich_client_id(&self, configs: &ConfigSet, client_id: &mut String) {
1632        #[derive(Debug, Deserialize)]
1633        struct EnrichmentRule {
1634            #[serde(deserialize_with = "deserialize_regex")]
1635            pattern: Regex,
1636            payload: String,
1637        }
1638
1639        fn deserialize_regex<'de, D>(deserializer: D) -> Result<Regex, D::Error>
1640        where
1641            D: Deserializer<'de>,
1642        {
1643            let buf = String::deserialize(deserializer)?;
1644            Regex::new(&buf).map_err(serde::de::Error::custom)
1645        }
1646
1647        let rules = KAFKA_CLIENT_ID_ENRICHMENT_RULES.get(configs);
1648        let rules = match serde_json::from_value::<Vec<EnrichmentRule>>(rules) {
1649            Ok(rules) => rules,
1650            Err(e) => {
1651                warn!(%e, "failed to decode kafka_client_id_enrichment_rules");
1652                return;
1653            }
1654        };
1655
1656        // Check every rule against every broker. Rules are matched in the order
1657        // that they are specified. It is usually a configuration error if
1658        // multiple rules match the same list of Kafka brokers, but we
1659        // nonetheless want to provide well defined semantics.
1660        debug!(?self.brokers, "evaluating client ID enrichment rules");
1661        for rule in rules {
1662            let is_match = self
1663                .brokers
1664                .iter()
1665                .any(|b| rule.pattern.is_match(&b.address));
1666            debug!(?rule, is_match, "evaluated client ID enrichment rule");
1667            if is_match {
1668                client_id.push('-');
1669                client_id.push_str(&rule.payload);
1670            }
1671        }
1672    }
1673
1674    /// Creates a Kafka client for the connection.
1675    pub async fn create_with_context<C, T>(
1676        &self,
1677        storage_configuration: &StorageConfiguration,
1678        context: C,
1679        extra_options: &BTreeMap<&str, String>,
1680        in_task: InTask,
1681    ) -> Result<T, ContextCreationError>
1682    where
1683        C: ClientContext,
1684        T: FromClientConfigAndContext<TunnelingClientContext<C>>,
1685    {
1686        let mut options = self.options.clone();
1687
1688        // Ensure that Kafka topics are *not* automatically created when
1689        // consuming, producing, or fetching metadata for a topic. This ensures
1690        // that we don't accidentally create topics with the wrong number of
1691        // partitions.
1692        options.insert("allow.auto.create.topics".into(), "false".into());
1693
1694        let brokers = match &self.default_tunnel {
1695            Tunnel::AwsPrivatelink(t) => {
1696                assert!(&self.brokers.is_empty());
1697
1698                let algo = KAFKA_DEFAULT_AWS_PRIVATELINK_ENDPOINT_IDENTIFICATION_ALGORITHM
1699                    .get(storage_configuration.config_set());
1700                options.insert("ssl.endpoint.identification.algorithm".into(), algo.into());
1701
1702                // When using a default privatelink tunnel broker/brokers cannot be specified
1703                // instead the tunnel connection_id and port are used for the initial connection.
1704                format!(
1705                    "{}:{}",
1706                    vpc_endpoint_host(
1707                        t.connection_id,
1708                        None, // Default tunnel does not support availability zones.
1709                    ),
1710                    t.port.unwrap_or(9092)
1711                )
1712            }
1713            Tunnel::AwsPrivatelinks(_pl) => {
1714                let algo = KAFKA_DEFAULT_AWS_PRIVATELINK_ENDPOINT_IDENTIFICATION_ALGORITHM
1715                    .get(storage_configuration.config_set());
1716                options.insert("ssl.endpoint.identification.algorithm".into(), algo.into());
1717
1718                if self.brokers.is_empty() {
1719                    return Err(ContextCreationError::Other(anyhow::anyhow!(
1720                        "at least one static broker is required when using BROKER or BROKERS"
1721                    )));
1722                }
1723                self.brokers.iter().map(|b| &b.address).join(",")
1724            }
1725            _ => self.brokers.iter().map(|b| &b.address).join(","),
1726        };
1727        options.insert("bootstrap.servers".into(), brokers.clone().into());
1728        let security_protocol = match (self.tls.is_some(), self.sasl.is_some()) {
1729            (false, false) => "PLAINTEXT",
1730            (true, false) => "SSL",
1731            (false, true) => "SASL_PLAINTEXT",
1732            (true, true) => "SASL_SSL",
1733        };
1734        info!(
1735            "kafka: create_with_context bootstrap.servers={brokers}, security_protocol={security_protocol}"
1736        );
1737        options.insert("security.protocol".into(), security_protocol.into());
1738        if let Some(tls) = &self.tls {
1739            if let Some(root_cert) = &tls.root_cert {
1740                options.insert("ssl.ca.pem".into(), root_cert.clone());
1741            }
1742            if let Some(identity) = &tls.identity {
1743                options.insert("ssl.key.pem".into(), StringOrSecret::Secret(identity.key));
1744                options.insert("ssl.certificate.pem".into(), identity.cert.clone());
1745            }
1746        }
1747        if let Some(sasl) = &self.sasl {
1748            options.insert("sasl.mechanisms".into(), (&sasl.mechanism).into());
1749            options.insert("sasl.username".into(), sasl.username.clone());
1750            if let Some(password) = sasl.password {
1751                options.insert("sasl.password".into(), StringOrSecret::Secret(password));
1752            }
1753        }
1754
1755        options.insert(
1756            "retry.backoff.ms".into(),
1757            KAFKA_RETRY_BACKOFF
1758                .get(storage_configuration.config_set())
1759                .as_millis()
1760                .into(),
1761        );
1762        options.insert(
1763            "retry.backoff.max.ms".into(),
1764            KAFKA_RETRY_BACKOFF_MAX
1765                .get(storage_configuration.config_set())
1766                .as_millis()
1767                .into(),
1768        );
1769        options.insert(
1770            "reconnect.backoff.ms".into(),
1771            KAFKA_RECONNECT_BACKOFF
1772                .get(storage_configuration.config_set())
1773                .as_millis()
1774                .into(),
1775        );
1776        options.insert(
1777            "reconnect.backoff.max.ms".into(),
1778            KAFKA_RECONNECT_BACKOFF_MAX
1779                .get(storage_configuration.config_set())
1780                .as_millis()
1781                .into(),
1782        );
1783
1784        let mut config = mz_kafka_util::client::create_new_client_config(
1785            storage_configuration
1786                .connection_context
1787                .librdkafka_log_level,
1788            storage_configuration.parameters.kafka_timeout_config,
1789        );
1790        for (k, v) in options {
1791            config.set(
1792                k,
1793                v.get_string(
1794                    in_task,
1795                    &storage_configuration.connection_context.secrets_reader,
1796                )
1797                .await
1798                .context("reading kafka secret")?,
1799            );
1800        }
1801        for (k, v) in extra_options {
1802            config.set(*k, v);
1803        }
1804
1805        let aws_config = match self.sasl.as_ref().and_then(|sasl| sasl.aws.as_ref()) {
1806            None => None,
1807            Some(aws) => Some(
1808                aws.connection
1809                    .load_sdk_config(
1810                        &storage_configuration.connection_context,
1811                        aws.connection_id,
1812                        in_task,
1813                        ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
1814                    )
1815                    .await?,
1816            ),
1817        };
1818
1819        let mut context = TunnelingClientContext::new(
1820            context,
1821            Handle::current(),
1822            storage_configuration
1823                .connection_context
1824                .ssh_tunnel_manager
1825                .clone(),
1826            storage_configuration.parameters.ssh_timeout_config,
1827            aws_config,
1828            in_task,
1829            ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
1830        );
1831
1832        match &self.default_tunnel {
1833            Tunnel::Direct => {
1834                // By default, don't offer a default override for broker address lookup.
1835            }
1836            Tunnel::AwsPrivatelink(pl) => {
1837                context.set_default_tunnel(TunnelConfig::StaticHost(
1838                    // Possible bug: We have been ignoring the configured port.
1839                    KafkaConnection::from_default_aws_privatelink(pl).host,
1840                ));
1841            }
1842            Tunnel::AwsPrivatelinks(pl) => {
1843                context.set_default_tunnel(TunnelConfig::Rules(
1844                    KafkaConnection::from_aws_privatelinks(pl),
1845                ));
1846            }
1847            Tunnel::Ssh(ssh_tunnel) => {
1848                let secret = storage_configuration
1849                    .connection_context
1850                    .secrets_reader
1851                    .read_in_task_if(in_task, ssh_tunnel.connection_id)
1852                    .await?;
1853                let key_pair = SshKeyPair::from_bytes(&secret)?;
1854
1855                // Ensure any ssh-bastion address we connect to is resolved to an external address.
1856                let resolved = resolve_address(
1857                    &ssh_tunnel.connection.host,
1858                    ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
1859                )
1860                .await?;
1861                context.set_default_tunnel(TunnelConfig::Ssh(SshTunnelConfig {
1862                    host: resolved
1863                        .iter()
1864                        .map(|a| a.to_string())
1865                        .collect::<BTreeSet<_>>(),
1866                    port: ssh_tunnel.connection.port,
1867                    user: ssh_tunnel.connection.user.clone(),
1868                    key_pair,
1869                }));
1870            }
1871        }
1872        info!(
1873            "kafka: tunnel config set to {}",
1874            match &self.default_tunnel {
1875                Tunnel::Direct => "Direct".to_string(),
1876                Tunnel::AwsPrivatelink(_) => "AwsPrivatelink (static host)".to_string(),
1877                Tunnel::AwsPrivatelinks(pl) =>
1878                    format!("AwsPrivatelinks ({} rules)", pl.rules.len()),
1879                Tunnel::Ssh(_) => "Ssh".to_string(),
1880            }
1881        );
1882
1883        // Here, we preemptively rewrite broker addresses.
1884        // In concept, this overlaps with 'TunnelingClientContext::resolve_broker_addr'.
1885        for broker in &self.brokers {
1886            let mut addr_parts = broker.address.splitn(2, ':');
1887            let addr = BrokerAddr {
1888                host: addr_parts
1889                    .next()
1890                    .context("BROKER is not address:port")?
1891                    .into(),
1892                port: addr_parts
1893                    .next()
1894                    .unwrap_or("9092")
1895                    .parse()
1896                    .context("parsing BROKER port")?,
1897            };
1898            match &broker.tunnel {
1899                Tunnel::Direct => {
1900                    // By default, don't override broker address lookup.
1901                    //
1902                    // N.B.
1903                    //
1904                    // We _could_ pre-setup the default ssh tunnel for all known brokers here, but
1905                    // we avoid doing because:
1906                    // - Its not necessary.
1907                    // - Not doing so makes it easier to test the `FailedDefaultSshTunnel` path
1908                    // in the `TunnelingClientContext`.
1909                }
1910                Tunnel::AwsPrivatelink(aws_privatelink) => {
1911                    context.add_broker_rewrite(
1912                        addr,
1913                        KafkaConnection::from_aws_privatelink(aws_privatelink),
1914                    );
1915                }
1916                Tunnel::AwsPrivatelinks(_) => unreachable!(
1917                    "Individually predefined brokers do not use rule-based PrivateLinks routing."
1918                ),
1919                Tunnel::Ssh(ssh_tunnel) => {
1920                    // Ensure any SSH bastion address we connect to is resolved to an external address.
1921                    let ssh_host_resolved = resolve_address(
1922                        &ssh_tunnel.connection.host,
1923                        ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
1924                    )
1925                    .await?;
1926                    context
1927                        .add_ssh_tunnel(
1928                            addr,
1929                            SshTunnelConfig {
1930                                host: ssh_host_resolved
1931                                    .iter()
1932                                    .map(|a| a.to_string())
1933                                    .collect::<BTreeSet<_>>(),
1934                                port: ssh_tunnel.connection.port,
1935                                user: ssh_tunnel.connection.user.clone(),
1936                                key_pair: SshKeyPair::from_bytes(
1937                                    &storage_configuration
1938                                        .connection_context
1939                                        .secrets_reader
1940                                        .read_in_task_if(in_task, ssh_tunnel.connection_id)
1941                                        .await?,
1942                                )?,
1943                            },
1944                        )
1945                        .await
1946                        .map_err(ContextCreationError::Ssh)?;
1947                }
1948            }
1949        }
1950
1951        Ok(mz_kafka_util::client::create_with_context(
1952            &config, context,
1953        )?)
1954    }
1955
1956    async fn validate(
1957        &self,
1958        _id: CatalogItemId,
1959        storage_configuration: &StorageConfiguration,
1960    ) -> Result<(), anyhow::Error> {
1961        let (context, error_rx) = MzClientContext::with_errors();
1962        let consumer: BaseConsumer<_> = self
1963            .create_with_context(
1964                storage_configuration,
1965                context,
1966                &BTreeMap::new(),
1967                // We are in a normal tokio context during validation, already.
1968                InTask::No,
1969            )
1970            .await?;
1971        let consumer = Arc::new(consumer);
1972
1973        let timeout = storage_configuration
1974            .parameters
1975            .kafka_timeout_config
1976            .fetch_metadata_timeout;
1977
1978        // librdkafka doesn't expose an API for determining whether a connection to
1979        // the Kafka cluster has been successfully established. So we make a
1980        // metadata request, though we don't care about the results, so that we can
1981        // report any errors making that request. If the request succeeds, we know
1982        // we were able to contact at least one broker, and that's a good proxy for
1983        // being able to contact all the brokers in the cluster.
1984        //
1985        // The downside of this approach is it produces a generic error message like
1986        // "metadata fetch error" with no additional details. The real networking
1987        // error is buried in the librdkafka logs, which are not visible to users.
1988        info!("kafka: starting connection validation via fetch_metadata (timeout={timeout:?})");
1989        let result = mz_ore::task::spawn_blocking(|| "kafka_get_metadata", {
1990            let consumer = Arc::clone(&consumer);
1991            move || consumer.fetch_metadata(None, timeout)
1992        })
1993        .await;
1994        info!(
1995            "kafka: connection validation result: {}",
1996            if result.is_ok() { "success" } else { "failed" },
1997        );
1998        match result {
1999            Ok(_) => Ok(()),
2000            // The error returned by `fetch_metadata` does not provide any details which makes for
2001            // a crappy user facing error message. For this reason we attempt to grab a better
2002            // error message from the client context, which should contain any error logs emitted
2003            // by librdkafka, and fallback to the generic error if there is nothing there.
2004            Err(err) => {
2005                // Multiple errors might have been logged during this validation but some are more
2006                // relevant than others. Specifically, we prefer non-internal errors over internal
2007                // errors since those give much more useful information to the users.
2008                let main_err = error_rx.try_iter().reduce(|cur, new| match cur {
2009                    MzKafkaError::Internal(_) => new,
2010                    _ => cur,
2011                });
2012
2013                // Don't drop the consumer until after we've drained the errors
2014                // channel. Dropping the consumer can introduce spurious errors.
2015                // See database-issues#7432.
2016                drop(consumer);
2017
2018                match main_err {
2019                    Some(err) => Err(err.into()),
2020                    None => Err(err.into()),
2021                }
2022            }
2023        }
2024    }
2025
2026    /// The "default" PrivateLink connection is used for bootstrapping Kafka.
2027    fn from_default_aws_privatelink(pl: &AwsPrivatelink) -> BrokerRewrite {
2028        BrokerRewrite {
2029            host: vpc_endpoint_host(
2030                pl.connection_id,
2031                None, // Default tunnel does not support availability zones.
2032            ),
2033            port: pl.port,
2034        }
2035    }
2036
2037    /// The "not default" PrivateLink connections are used for routing to specific Kafka brokers.
2038    fn from_aws_privatelink(pl: &AwsPrivatelink) -> BrokerRewrite {
2039        BrokerRewrite {
2040            host: vpc_endpoint_host(pl.connection_id, pl.availability_zone.as_deref()),
2041            port: pl.port,
2042        }
2043    }
2044
2045    fn from_aws_privatelink_rule(
2046        AwsPrivatelinkRule { pattern, to }: &AwsPrivatelinkRule,
2047    ) -> (mz_kafka_util::client::ConnectionRulePattern, BrokerRewrite) {
2048        (
2049            mz_kafka_util::client::ConnectionRulePattern {
2050                prefix_wildcard: pattern.prefix_wildcard,
2051                literal_match: pattern.literal_match.clone(),
2052                suffix_wildcard: pattern.suffix_wildcard,
2053            },
2054            KafkaConnection::from_aws_privatelink(to),
2055        )
2056    }
2057
2058    fn from_aws_privatelinks(pl: &AwsPrivatelinks) -> HostMappingRules {
2059        HostMappingRules {
2060            rules: pl
2061                .rules
2062                .iter()
2063                .map(KafkaConnection::from_aws_privatelink_rule)
2064                .collect_vec(),
2065        }
2066    }
2067}
2068
2069impl<C: ConnectionAccess> AlterCompatible for KafkaConnection<C> {
2070    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
2071        let KafkaConnection {
2072            brokers: _,
2073            default_tunnel: _,
2074            progress_topic,
2075            progress_topic_options,
2076            options: _,
2077            tls: _,
2078            sasl: _,
2079        } = self;
2080
2081        let compatibility_checks = [
2082            (progress_topic == &other.progress_topic, "progress_topic"),
2083            (
2084                progress_topic_options == &other.progress_topic_options,
2085                "progress_topic_options",
2086            ),
2087        ];
2088
2089        for (compatible, field) in compatibility_checks {
2090            if !compatible {
2091                tracing::warn!(
2092                    "KafkaConnection incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
2093                    self,
2094                    other
2095                );
2096
2097                return Err(AlterError { id });
2098            }
2099        }
2100
2101        Ok(())
2102    }
2103}
2104
2105/// A connection to a Confluent Schema Registry.
2106#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2107pub struct CsrConnection<C: ConnectionAccess = InlinedConnection> {
2108    /// The URL of the schema registry.
2109    pub url: Url,
2110    /// Trusted root TLS certificate in PEM format.
2111    pub tls_root_cert: Option<StringOrSecret>,
2112    /// An optional TLS client certificate for authentication with the schema
2113    /// registry.
2114    pub tls_identity: Option<TlsIdentity>,
2115    /// Optional HTTP authentication credentials for the schema registry.
2116    pub http_auth: Option<CsrConnectionHttpAuth>,
2117    /// A tunnel through which to route traffic.
2118    pub tunnel: Tunnel<C>,
2119}
2120
2121impl<R: ConnectionResolver> IntoInlineConnection<CsrConnection, R>
2122    for CsrConnection<ReferencedConnection>
2123{
2124    fn into_inline_connection(self, r: R) -> CsrConnection {
2125        let CsrConnection {
2126            url,
2127            tls_root_cert,
2128            tls_identity,
2129            http_auth,
2130            tunnel,
2131        } = self;
2132        CsrConnection {
2133            url,
2134            tls_root_cert,
2135            tls_identity,
2136            http_auth,
2137            tunnel: tunnel.into_inline_connection(r),
2138        }
2139    }
2140}
2141
2142impl<C: ConnectionAccess> CsrConnection<C> {
2143    fn validate_by_default(&self) -> bool {
2144        true
2145    }
2146}
2147
2148impl CsrConnection {
2149    /// Constructs a schema registry client from the connection.
2150    pub async fn connect(
2151        &self,
2152        storage_configuration: &StorageConfiguration,
2153        in_task: InTask,
2154    ) -> Result<mz_ccsr::Client, CsrConnectError> {
2155        let mut client_config = mz_ccsr::ClientConfig::new(self.url.clone());
2156        if let Some(root_cert) = &self.tls_root_cert {
2157            let root_cert = root_cert
2158                .get_string(
2159                    in_task,
2160                    &storage_configuration.connection_context.secrets_reader,
2161                )
2162                .await?;
2163            let root_cert = Certificate::from_pem(root_cert.as_bytes())?;
2164            client_config = client_config.add_root_certificate(root_cert);
2165        }
2166
2167        if let Some(tls_identity) = &self.tls_identity {
2168            let key = &storage_configuration
2169                .connection_context
2170                .secrets_reader
2171                .read_string_in_task_if(in_task, tls_identity.key)
2172                .await?;
2173            let cert = tls_identity
2174                .cert
2175                .get_string(
2176                    in_task,
2177                    &storage_configuration.connection_context.secrets_reader,
2178                )
2179                .await?;
2180            let ident = Identity::from_pem(key.as_bytes(), cert.as_bytes())?;
2181            client_config = client_config.identity(ident);
2182        }
2183
2184        if let Some(http_auth) = &self.http_auth {
2185            let username = http_auth
2186                .username
2187                .get_string(
2188                    in_task,
2189                    &storage_configuration.connection_context.secrets_reader,
2190                )
2191                .await?;
2192            let password = match http_auth.password {
2193                None => None,
2194                Some(password) => Some(
2195                    storage_configuration
2196                        .connection_context
2197                        .secrets_reader
2198                        .read_string_in_task_if(in_task, password)
2199                        .await?,
2200                ),
2201            };
2202            client_config = client_config.auth(username, password);
2203        }
2204
2205        // TODO: use types to enforce that the URL has a string hostname.
2206        let host = self
2207            .url
2208            .host_str()
2209            .ok_or_else(|| anyhow!("url missing host"))?;
2210        match &self.tunnel {
2211            Tunnel::Direct => {
2212                // Ensure any host we connect to is resolved to an external address.
2213                let resolved = resolve_address(
2214                    host,
2215                    ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
2216                )
2217                .await?;
2218                client_config = client_config.resolve_to_addrs(
2219                    host,
2220                    &resolved
2221                        .iter()
2222                        .map(|addr| SocketAddr::new(*addr, 0))
2223                        .collect::<Vec<_>>(),
2224                )
2225            }
2226            Tunnel::Ssh(ssh_tunnel) => {
2227                let ssh_tunnel = ssh_tunnel
2228                    .connect(
2229                        storage_configuration,
2230                        host,
2231                        // Honor the URL scheme's default port (443 for https,
2232                        // 80 for http) if no explicit port was provided.
2233                        self.url.port_or_known_default().unwrap_or(80),
2234                        in_task,
2235                    )
2236                    .await
2237                    .map_err(CsrConnectError::Ssh)?;
2238
2239                // Carefully inject the SSH tunnel into the client
2240                // configuration. This is delicate because we need TLS
2241                // verification to continue to use the remote hostname rather
2242                // than the tunnel hostname.
2243
2244                client_config = client_config
2245                    // `resolve_to_addrs` allows us to rewrite the hostname
2246                    // at the DNS level, which means the TCP connection is
2247                    // correctly routed through the tunnel, but TLS verification
2248                    // is still performed against the remote hostname.
2249                    // Unfortunately the port here is ignored if the URL also
2250                    // specifies a port...
2251                    .resolve_to_addrs(host, &[SocketAddr::new(ssh_tunnel.local_addr().ip(), 0)])
2252                    // ...so we also dynamically rewrite the URL to use the
2253                    // current port for the SSH tunnel.
2254                    //
2255                    // WARNING: this is brittle, because we only dynamically
2256                    // update the client configuration with the tunnel *port*,
2257                    // and not the hostname This works fine in practice, because
2258                    // only the SSH tunnel port will change if the tunnel fails
2259                    // and has to be restarted (the hostname is always
2260                    // 127.0.0.1)--but this is an an implementation detail of
2261                    // the SSH tunnel code that we're relying on.
2262                    .dynamic_url({
2263                        let remote_url = self.url.clone();
2264                        move || {
2265                            let mut url = remote_url.clone();
2266                            url.set_port(Some(ssh_tunnel.local_addr().port()))
2267                                .expect("cannot fail");
2268                            url
2269                        }
2270                    });
2271            }
2272            Tunnel::AwsPrivatelink(connection) => {
2273                assert_none!(connection.port);
2274
2275                let privatelink_host = mz_cloud_resources::vpc_endpoint_host(
2276                    connection.connection_id,
2277                    connection.availability_zone.as_deref(),
2278                );
2279                let addrs: Vec<_> = net::lookup_host((privatelink_host, 0))
2280                    .await
2281                    .context("resolving PrivateLink host")?
2282                    .collect();
2283                client_config = client_config.resolve_to_addrs(host, &addrs)
2284            }
2285            Tunnel::AwsPrivatelinks(_) => {
2286                unreachable!("MATCHING broker rules are only available for Kafka connections.");
2287            }
2288        }
2289
2290        Ok(client_config.build()?)
2291    }
2292
2293    async fn validate(
2294        &self,
2295        _id: CatalogItemId,
2296        storage_configuration: &StorageConfiguration,
2297    ) -> Result<(), anyhow::Error> {
2298        let client = self
2299            .connect(
2300                storage_configuration,
2301                // We are in a normal tokio context during validation, already.
2302                InTask::No,
2303            )
2304            .await?;
2305        client.list_subjects().await?;
2306        Ok(())
2307    }
2308}
2309
2310impl<C: ConnectionAccess> AlterCompatible for CsrConnection<C> {
2311    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
2312        let CsrConnection {
2313            tunnel,
2314            // All non-tunnel fields may change
2315            url: _,
2316            tls_root_cert: _,
2317            tls_identity: _,
2318            http_auth: _,
2319        } = self;
2320
2321        let compatibility_checks = [(tunnel.alter_compatible(id, &other.tunnel).is_ok(), "tunnel")];
2322
2323        for (compatible, field) in compatibility_checks {
2324            if !compatible {
2325                tracing::warn!(
2326                    "CsrConnection incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
2327                    self,
2328                    other
2329                );
2330
2331                return Err(AlterError { id });
2332            }
2333        }
2334        Ok(())
2335    }
2336}
2337
2338/// A connection to an AWS Glue Schema Registry.
2339///
2340/// AWS credentials, region, and endpoint are inherited from the referenced
2341/// [`AwsConnection`]; this struct only carries the per-registry settings.
2342#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2343pub struct GlueSchemaRegistryConnection<C: ConnectionAccess = InlinedConnection> {
2344    /// The referenced AWS connection that supplies credentials, region, and
2345    /// (optional) endpoint.
2346    pub aws_connection: AwsConnectionReference<C>,
2347    /// The Glue Schema Registry name within the AWS account/region.
2348    pub registry_name: String,
2349}
2350
2351impl<R: ConnectionResolver> IntoInlineConnection<GlueSchemaRegistryConnection, R>
2352    for GlueSchemaRegistryConnection<ReferencedConnection>
2353{
2354    fn into_inline_connection(self, r: R) -> GlueSchemaRegistryConnection {
2355        let GlueSchemaRegistryConnection {
2356            aws_connection,
2357            registry_name,
2358        } = self;
2359        GlueSchemaRegistryConnection {
2360            aws_connection: aws_connection.into_inline_connection(&r),
2361            registry_name,
2362        }
2363    }
2364}
2365
2366impl<C: ConnectionAccess> GlueSchemaRegistryConnection<C> {
2367    fn validate_by_default(&self) -> bool {
2368        // Matches CSR: default-validate so a bad registry name fails at
2369        // `CREATE CONNECTION` rather than surfacing later on first use.
2370        // Users can still opt out with `WITH (VALIDATE = false)`.
2371        true
2372    }
2373}
2374
2375impl GlueSchemaRegistryConnection {
2376    async fn validate(
2377        &self,
2378        _id: CatalogItemId,
2379        storage_configuration: &StorageConfiguration,
2380    ) -> Result<(), anyhow::Error> {
2381        let enforce_external_addresses =
2382            crate::dyncfgs::ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set());
2383        let sdk_config = self
2384            .aws_connection
2385            .connection
2386            .load_sdk_config(
2387                &storage_configuration.connection_context,
2388                self.aws_connection.connection_id,
2389                // We are in a normal tokio context during validation.
2390                InTask::No,
2391                enforce_external_addresses,
2392            )
2393            .await?;
2394        let client = mz_aws_glue_schema_registry::ClientConfig::new(sdk_config).build();
2395        match client.get_registry(&self.registry_name).await {
2396            Ok(_) => Ok(()),
2397            Err(mz_aws_glue_schema_registry::GetRegistryError::NotFound) => Err(anyhow!(
2398                "AWS Glue Schema Registry {:?} does not exist in the configured account/region",
2399                self.registry_name
2400            )),
2401            Err(err) => Err(anyhow::Error::new(err).context(format!(
2402                "failed to validate AWS Glue Schema Registry connection (registry={:?})",
2403                self.registry_name
2404            ))),
2405        }
2406    }
2407}
2408
2409impl<C: ConnectionAccess> AlterCompatible for GlueSchemaRegistryConnection<C> {
2410    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
2411        let GlueSchemaRegistryConnection {
2412            registry_name,
2413            // The referenced AWS connection itself may be swapped; matches
2414            // the permissive policy of MySqlConnection / SqlServerConnection.
2415            aws_connection: _,
2416        } = self;
2417
2418        let compatibility_checks = [(registry_name == &other.registry_name, "registry_name")];
2419
2420        for (compatible, field) in compatibility_checks {
2421            if !compatible {
2422                tracing::warn!(
2423                    "GlueSchemaRegistryConnection incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
2424                    self,
2425                    other
2426                );
2427
2428                return Err(AlterError { id });
2429            }
2430        }
2431        Ok(())
2432    }
2433}
2434
2435/// A TLS key pair used for client identity.
2436#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2437pub struct TlsIdentity {
2438    /// The client's TLS public certificate in PEM format.
2439    pub cert: StringOrSecret,
2440    /// The ID of the secret containing the client's TLS private key in PEM
2441    /// format.
2442    pub key: CatalogItemId,
2443}
2444
2445/// HTTP authentication credentials in a [`CsrConnection`].
2446#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2447pub struct CsrConnectionHttpAuth {
2448    /// The username.
2449    pub username: StringOrSecret,
2450    /// The ID of the secret containing the password, if any.
2451    pub password: Option<CatalogItemId>,
2452}
2453
2454/// A connection to a PostgreSQL server.
2455#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2456pub struct PostgresConnection<C: ConnectionAccess = InlinedConnection> {
2457    /// The hostname of the server.
2458    pub host: String,
2459    /// The port of the server.
2460    pub port: u16,
2461    /// The name of the database to connect to.
2462    pub database: String,
2463    /// The username to authenticate as.
2464    pub user: StringOrSecret,
2465    /// An optional password for authentication.
2466    pub password: Option<CatalogItemId>,
2467    /// A tunnel through which to route traffic.
2468    pub tunnel: Tunnel<C>,
2469    /// Whether to use TLS for encryption, authentication, or both.
2470    pub tls_mode: SslMode,
2471    /// An optional root TLS certificate in PEM format, to verify the server's
2472    /// identity.
2473    pub tls_root_cert: Option<StringOrSecret>,
2474    /// An optional TLS client certificate for authentication.
2475    pub tls_identity: Option<TlsIdentity>,
2476    /// Reference to the AWS connection to use for IAM authentication with
2477    /// Amazon RDS or Aurora, in place of a password.
2478    pub aws_connection: Option<AwsConnectionReference<C>>,
2479}
2480
2481impl<R: ConnectionResolver> IntoInlineConnection<PostgresConnection, R>
2482    for PostgresConnection<ReferencedConnection>
2483{
2484    fn into_inline_connection(self, r: R) -> PostgresConnection {
2485        let PostgresConnection {
2486            host,
2487            port,
2488            database,
2489            user,
2490            password,
2491            tunnel,
2492            tls_mode,
2493            tls_root_cert,
2494            tls_identity,
2495            aws_connection,
2496        } = self;
2497
2498        PostgresConnection {
2499            host,
2500            port,
2501            database,
2502            user,
2503            password,
2504            tunnel: tunnel.into_inline_connection(&r),
2505            tls_mode,
2506            tls_root_cert,
2507            tls_identity,
2508            aws_connection: aws_connection.map(|aws| aws.into_inline_connection(&r)),
2509        }
2510    }
2511}
2512
2513impl<C: ConnectionAccess> PostgresConnection<C> {
2514    fn validate_by_default(&self) -> bool {
2515        true
2516    }
2517}
2518
2519impl PostgresConnection<InlinedConnection> {
2520    pub async fn config(
2521        &self,
2522        secrets_reader: &Arc<dyn mz_secrets::SecretsReader>,
2523        storage_configuration: &StorageConfiguration,
2524        in_task: InTask,
2525    ) -> Result<mz_postgres_util::Config, anyhow::Error> {
2526        let params = &storage_configuration.parameters;
2527
2528        let mut config = tokio_postgres::Config::new();
2529        config
2530            .host(&self.host)
2531            .port(self.port)
2532            .dbname(&self.database)
2533            .user(&self.user.get_string(in_task, secrets_reader).await?)
2534            .ssl_mode(self.tls_mode)
2535            .application_name("materialize");
2536        if let Some(password) = self.password {
2537            let password = secrets_reader
2538                .read_string_in_task_if(in_task, password)
2539                .await?;
2540            config.password(password);
2541        }
2542        if let Some(tls_root_cert) = &self.tls_root_cert {
2543            let tls_root_cert = tls_root_cert.get_string(in_task, secrets_reader).await?;
2544            config.ssl_root_cert(tls_root_cert.as_bytes());
2545        }
2546        if let Some(tls_identity) = &self.tls_identity {
2547            let cert = tls_identity
2548                .cert
2549                .get_string(in_task, secrets_reader)
2550                .await?;
2551            let key = secrets_reader
2552                .read_string_in_task_if(in_task, tls_identity.key)
2553                .await?;
2554            config.ssl_cert(cert.as_bytes()).ssl_key(key.as_bytes());
2555        }
2556
2557        if let Some(connect_timeout) = params.pg_source_connect_timeout {
2558            config.connect_timeout(connect_timeout);
2559        }
2560        if let Some(keepalives_retries) = params.pg_source_tcp_keepalives_retries {
2561            config.keepalives_retries(keepalives_retries);
2562        }
2563        if let Some(keepalives_idle) = params.pg_source_tcp_keepalives_idle {
2564            config.keepalives_idle(keepalives_idle);
2565        }
2566        if let Some(keepalives_interval) = params.pg_source_tcp_keepalives_interval {
2567            config.keepalives_interval(keepalives_interval);
2568        }
2569        if let Some(tcp_user_timeout) = params.pg_source_tcp_user_timeout {
2570            config.tcp_user_timeout(tcp_user_timeout);
2571        }
2572
2573        let mut options = vec![];
2574        if let Some(wal_sender_timeout) = params.pg_source_wal_sender_timeout {
2575            options.push(format!(
2576                "--wal_sender_timeout={}",
2577                wal_sender_timeout.as_millis()
2578            ));
2579        };
2580        if params.pg_source_tcp_configure_server {
2581            if let Some(keepalives_retries) = params.pg_source_tcp_keepalives_retries {
2582                options.push(format!("--tcp_keepalives_count={}", keepalives_retries));
2583            }
2584            if let Some(keepalives_idle) = params.pg_source_tcp_keepalives_idle {
2585                options.push(format!(
2586                    "--tcp_keepalives_idle={}",
2587                    keepalives_idle.as_secs()
2588                ));
2589            }
2590            if let Some(keepalives_interval) = params.pg_source_tcp_keepalives_interval {
2591                options.push(format!(
2592                    "--tcp_keepalives_interval={}",
2593                    keepalives_interval.as_secs()
2594                ));
2595            }
2596            if let Some(tcp_user_timeout) = params.pg_source_tcp_user_timeout {
2597                options.push(format!(
2598                    "--tcp_user_timeout={}",
2599                    tcp_user_timeout.as_millis()
2600                ));
2601            }
2602        }
2603        config.options(options.join(" ").as_str());
2604
2605        let tunnel = match &self.tunnel {
2606            Tunnel::Direct => {
2607                // Ensure any host we connect to is resolved to an external address.
2608                let resolved = resolve_address(
2609                    &self.host,
2610                    ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
2611                )
2612                .await?;
2613                mz_postgres_util::TunnelConfig::Direct {
2614                    resolved_ips: Some(resolved),
2615                }
2616            }
2617            Tunnel::Ssh(SshTunnel {
2618                connection_id,
2619                connection,
2620            }) => {
2621                let secret = secrets_reader
2622                    .read_in_task_if(in_task, *connection_id)
2623                    .await?;
2624                let key_pair = SshKeyPair::from_bytes(&secret)?;
2625                // Ensure any ssh-bastion host we connect to is resolved to an external address.
2626                let resolved = resolve_address(
2627                    &connection.host,
2628                    ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
2629                )
2630                .await?;
2631                mz_postgres_util::TunnelConfig::Ssh {
2632                    config: SshTunnelConfig {
2633                        host: resolved
2634                            .iter()
2635                            .map(|a| a.to_string())
2636                            .collect::<BTreeSet<_>>(),
2637                        port: connection.port,
2638                        user: connection.user.clone(),
2639                        key_pair,
2640                    },
2641                }
2642            }
2643            Tunnel::AwsPrivatelink(connection) => {
2644                assert_none!(connection.port);
2645                mz_postgres_util::TunnelConfig::AwsPrivatelink {
2646                    connection_id: connection.connection_id,
2647                }
2648            }
2649            Tunnel::AwsPrivatelinks(_) => {
2650                unreachable!("MATCHING broker rules are only available for Kafka connections.");
2651            }
2652        };
2653
2654        let iam_auth = match self.aws_connection.as_ref() {
2655            None => None,
2656            Some(aws_ref) => Some(
2657                aws_ref
2658                    .connection
2659                    .load_rds_iam_auth(
2660                        &storage_configuration.connection_context,
2661                        aws_ref.connection_id,
2662                        in_task,
2663                        ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
2664                    )
2665                    .await?,
2666            ),
2667        };
2668
2669        Ok(mz_postgres_util::Config::new(
2670            config,
2671            tunnel,
2672            params.ssh_timeout_config,
2673            in_task,
2674            iam_auth,
2675        )?)
2676    }
2677
2678    pub async fn validate(
2679        &self,
2680        _id: CatalogItemId,
2681        storage_configuration: &StorageConfiguration,
2682    ) -> Result<mz_postgres_util::Client, anyhow::Error> {
2683        let config = self
2684            .config(
2685                &storage_configuration.connection_context.secrets_reader,
2686                storage_configuration,
2687                // We are in a normal tokio context during validation, already.
2688                InTask::No,
2689            )
2690            .await?;
2691        let client = config
2692            .connect(
2693                "connection validation",
2694                &storage_configuration.connection_context.ssh_tunnel_manager,
2695            )
2696            .await?;
2697
2698        let wal_level = mz_postgres_util::get_wal_level(&client).await?;
2699
2700        if wal_level < mz_postgres_util::replication::WalLevel::Logical {
2701            Err(PostgresConnectionValidationError::InsufficientWalLevel { wal_level })?;
2702        }
2703
2704        let max_wal_senders = mz_postgres_util::get_max_wal_senders(&client).await?;
2705
2706        if max_wal_senders < 1 {
2707            Err(PostgresConnectionValidationError::ReplicationDisabled)?;
2708        }
2709
2710        let available_replication_slots =
2711            mz_postgres_util::available_replication_slots(&client).await?;
2712
2713        // We need 1 replication slot for the snapshots and 1 for the continuing replication
2714        if available_replication_slots < 2 {
2715            Err(
2716                PostgresConnectionValidationError::InsufficientReplicationSlotsAvailable {
2717                    count: 2,
2718                },
2719            )?;
2720        }
2721
2722        Ok(client)
2723    }
2724}
2725
2726#[derive(Debug, Clone, thiserror::Error)]
2727pub enum PostgresConnectionValidationError {
2728    #[error("PostgreSQL server has insufficient number of replication slots available")]
2729    InsufficientReplicationSlotsAvailable { count: usize },
2730    #[error("server must have wal_level >= logical, but has {wal_level}")]
2731    InsufficientWalLevel {
2732        wal_level: mz_postgres_util::replication::WalLevel,
2733    },
2734    #[error("replication disabled on server")]
2735    ReplicationDisabled,
2736}
2737
2738impl PostgresConnectionValidationError {
2739    pub fn detail(&self) -> Option<String> {
2740        match self {
2741            Self::InsufficientReplicationSlotsAvailable { count } => Some(format!(
2742                "executing this statement requires {} replication slot{}",
2743                count,
2744                if *count == 1 { "" } else { "s" }
2745            )),
2746            _ => None,
2747        }
2748    }
2749
2750    pub fn hint(&self) -> Option<String> {
2751        match self {
2752            Self::InsufficientReplicationSlotsAvailable { .. } => Some(
2753                "you might be able to wait for other sources to finish snapshotting and try again"
2754                    .into(),
2755            ),
2756            Self::ReplicationDisabled => Some("set max_wal_senders to a value > 0".into()),
2757            Self::InsufficientWalLevel { .. } => None,
2758        }
2759    }
2760}
2761
2762impl<C: ConnectionAccess> AlterCompatible for PostgresConnection<C> {
2763    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
2764        let PostgresConnection {
2765            tunnel,
2766            // All non-tunnel options may change arbitrarily
2767            host: _,
2768            port: _,
2769            database: _,
2770            user: _,
2771            password: _,
2772            tls_mode: _,
2773            tls_root_cert: _,
2774            tls_identity: _,
2775            aws_connection: _,
2776        } = self;
2777
2778        let compatibility_checks = [(tunnel.alter_compatible(id, &other.tunnel).is_ok(), "tunnel")];
2779
2780        for (compatible, field) in compatibility_checks {
2781            if !compatible {
2782                tracing::warn!(
2783                    "PostgresConnection incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
2784                    self,
2785                    other
2786                );
2787
2788                return Err(AlterError { id });
2789            }
2790        }
2791        Ok(())
2792    }
2793}
2794
2795/// Specifies how to tunnel a connection.
2796#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2797pub enum Tunnel<C: ConnectionAccess = InlinedConnection> {
2798    /// No tunneling.
2799    Direct,
2800    /// Via the specified SSH tunnel connection.
2801    Ssh(SshTunnel<C>),
2802    /// Via the specified AWS PrivateLink connection.
2803    AwsPrivatelink(AwsPrivatelink),
2804    AwsPrivatelinks(AwsPrivatelinks),
2805}
2806
2807impl<R: ConnectionResolver> IntoInlineConnection<Tunnel, R> for Tunnel<ReferencedConnection> {
2808    fn into_inline_connection(self, r: R) -> Tunnel {
2809        match self {
2810            Tunnel::Direct => Tunnel::Direct,
2811            Tunnel::Ssh(ssh) => Tunnel::Ssh(ssh.into_inline_connection(r)),
2812            Tunnel::AwsPrivatelink(awspl) => Tunnel::AwsPrivatelink(awspl),
2813            Tunnel::AwsPrivatelinks(x) => Tunnel::AwsPrivatelinks(x),
2814        }
2815    }
2816}
2817
2818impl<C: ConnectionAccess> AlterCompatible for Tunnel<C> {
2819    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
2820        let compatible = match (self, other) {
2821            (Self::Ssh(s), Self::Ssh(o)) => s.alter_compatible(id, o).is_ok(),
2822            (s, o) => s == o,
2823        };
2824
2825        if !compatible {
2826            tracing::warn!(
2827                "Tunnel incompatible:\nself:\n{:#?}\n\nother\n{:#?}",
2828                self,
2829                other
2830            );
2831
2832            return Err(AlterError { id });
2833        }
2834
2835        Ok(())
2836    }
2837}
2838
2839/// Specifies which MySQL SSL Mode to use:
2840/// <https://dev.mysql.com/doc/refman/8.0/en/connection-options.html#option_general_ssl-mode>
2841/// This is not available as an enum in the mysql-async crate, so we define our own.
2842#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2843pub enum MySqlSslMode {
2844    Disabled,
2845    Required,
2846    VerifyCa,
2847    VerifyIdentity,
2848}
2849
2850/// A connection to a MySQL server.
2851#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2852pub struct MySqlConnection<C: ConnectionAccess = InlinedConnection> {
2853    /// The hostname of the server.
2854    pub host: String,
2855    /// The port of the server.
2856    pub port: u16,
2857    /// The username to authenticate as.
2858    pub user: StringOrSecret,
2859    /// An optional password for authentication.
2860    pub password: Option<CatalogItemId>,
2861    /// A tunnel through which to route traffic.
2862    pub tunnel: Tunnel<C>,
2863    /// Whether to use TLS for encryption, verify the server's certificate, and identity.
2864    pub tls_mode: MySqlSslMode,
2865    /// An optional root TLS certificate in PEM format, to verify the server's
2866    /// identity.
2867    pub tls_root_cert: Option<StringOrSecret>,
2868    /// An optional TLS client certificate for authentication.
2869    pub tls_identity: Option<TlsIdentity>,
2870    /// Reference to the AWS connection information to be used for IAM authenitcation and
2871    /// assuming AWS roles.
2872    pub aws_connection: Option<AwsConnectionReference<C>>,
2873}
2874
2875impl<R: ConnectionResolver> IntoInlineConnection<MySqlConnection, R>
2876    for MySqlConnection<ReferencedConnection>
2877{
2878    fn into_inline_connection(self, r: R) -> MySqlConnection {
2879        let MySqlConnection {
2880            host,
2881            port,
2882            user,
2883            password,
2884            tunnel,
2885            tls_mode,
2886            tls_root_cert,
2887            tls_identity,
2888            aws_connection,
2889        } = self;
2890
2891        MySqlConnection {
2892            host,
2893            port,
2894            user,
2895            password,
2896            tunnel: tunnel.into_inline_connection(&r),
2897            tls_mode,
2898            tls_root_cert,
2899            tls_identity,
2900            aws_connection: aws_connection.map(|aws| aws.into_inline_connection(&r)),
2901        }
2902    }
2903}
2904
2905impl<C: ConnectionAccess> MySqlConnection<C> {
2906    fn validate_by_default(&self) -> bool {
2907        true
2908    }
2909}
2910
2911impl MySqlConnection<InlinedConnection> {
2912    pub async fn config(
2913        &self,
2914        secrets_reader: &Arc<dyn mz_secrets::SecretsReader>,
2915        storage_configuration: &StorageConfiguration,
2916        in_task: InTask,
2917    ) -> Result<mz_mysql_util::Config, anyhow::Error> {
2918        // TODO(roshan): Set appropriate connection timeouts
2919        let mut opts = mysql_async::OptsBuilder::default()
2920            .ip_or_hostname(&self.host)
2921            .tcp_port(self.port)
2922            .user(Some(&self.user.get_string(in_task, secrets_reader).await?));
2923
2924        if let Some(password) = self.password {
2925            let password = secrets_reader
2926                .read_string_in_task_if(in_task, password)
2927                .await?;
2928            opts = opts.pass(Some(password));
2929        }
2930
2931        // Our `MySqlSslMode` enum matches the official MySQL Client `--ssl-mode` parameter values
2932        // which uses opt-in security features (SSL, CA verification, & Identity verification).
2933        // The mysql_async crate `SslOpts` struct uses an opt-out mechanism for each of these, so
2934        // we need to appropriately disable features to match the intent of each enum value.
2935        let mut ssl_opts = match self.tls_mode {
2936            MySqlSslMode::Disabled => None,
2937            MySqlSslMode::Required => Some(
2938                mysql_async::SslOpts::default()
2939                    .with_danger_accept_invalid_certs(true)
2940                    .with_danger_skip_domain_validation(true),
2941            ),
2942            MySqlSslMode::VerifyCa => {
2943                Some(mysql_async::SslOpts::default().with_danger_skip_domain_validation(true))
2944            }
2945            MySqlSslMode::VerifyIdentity => Some(mysql_async::SslOpts::default()),
2946        };
2947
2948        if matches!(
2949            self.tls_mode,
2950            MySqlSslMode::VerifyCa | MySqlSslMode::VerifyIdentity
2951        ) {
2952            // Trust the platform's roots, not the Mozilla set compiled into
2953            // mysql_async, so a distrusted root goes away with an OS update.
2954            let native = rustls_native_certs::load_native_certs();
2955            for error in &native.errors {
2956                tracing::warn!("failed to load native root certs: {error}");
2957            }
2958            let mut roots: Vec<_> = native
2959                .certs
2960                .into_iter()
2961                .map(|cert| cert.to_vec().into())
2962                .collect();
2963            if let Some(tls_root_cert) = &self.tls_root_cert {
2964                let tls_root_cert = tls_root_cert.get_string(in_task, secrets_reader).await?;
2965                roots.push(tls_root_cert.into_bytes().into());
2966            }
2967            ssl_opts = ssl_opts.map(|opts| {
2968                opts.with_disable_built_in_roots(true)
2969                    .with_root_certs(roots)
2970            });
2971        }
2972
2973        if let Some(identity) = &self.tls_identity {
2974            let key = secrets_reader
2975                .read_string_in_task_if(in_task, identity.key)
2976                .await?;
2977            let cert = identity.cert.get_string(in_task, secrets_reader).await?;
2978            ssl_opts = ssl_opts.map(|opts| {
2979                opts.with_client_identity(Some(mysql_async::ClientIdentity::new(
2980                    cert.into_bytes().into(),
2981                    key.into_bytes().into(),
2982                )))
2983            });
2984        }
2985
2986        opts = opts.ssl_opts(ssl_opts);
2987
2988        let tunnel = match &self.tunnel {
2989            Tunnel::Direct => {
2990                // Ensure any host we connect to is resolved to an external address.
2991                let resolved = resolve_address(
2992                    &self.host,
2993                    ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
2994                )
2995                .await?;
2996                mz_mysql_util::TunnelConfig::Direct {
2997                    resolved_ips: Some(resolved),
2998                }
2999            }
3000            Tunnel::Ssh(SshTunnel {
3001                connection_id,
3002                connection,
3003            }) => {
3004                let secret = secrets_reader
3005                    .read_in_task_if(in_task, *connection_id)
3006                    .await?;
3007                let key_pair = SshKeyPair::from_bytes(&secret)?;
3008                // Ensure any ssh-bastion host we connect to is resolved to an external address.
3009                let resolved = resolve_address(
3010                    &connection.host,
3011                    ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
3012                )
3013                .await?;
3014                mz_mysql_util::TunnelConfig::Ssh {
3015                    config: SshTunnelConfig {
3016                        host: resolved
3017                            .iter()
3018                            .map(|a| a.to_string())
3019                            .collect::<BTreeSet<_>>(),
3020                        port: connection.port,
3021                        user: connection.user.clone(),
3022                        key_pair,
3023                    },
3024                }
3025            }
3026            Tunnel::AwsPrivatelink(connection) => {
3027                assert_none!(connection.port);
3028                mz_mysql_util::TunnelConfig::AwsPrivatelink {
3029                    connection_id: connection.connection_id,
3030                }
3031            }
3032            Tunnel::AwsPrivatelinks(_) => {
3033                unreachable!("MATCHING broker rules are only available for Kafka connections.");
3034            }
3035        };
3036
3037        let iam_auth = match self.aws_connection.as_ref() {
3038            None => None,
3039            Some(aws_ref) => Some(
3040                aws_ref
3041                    .connection
3042                    .load_rds_iam_auth(
3043                        &storage_configuration.connection_context,
3044                        aws_ref.connection_id,
3045                        in_task,
3046                        ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
3047                    )
3048                    .await?,
3049            ),
3050        };
3051
3052        Ok(mz_mysql_util::Config::new(
3053            opts,
3054            tunnel,
3055            storage_configuration.parameters.ssh_timeout_config,
3056            in_task,
3057            storage_configuration
3058                .parameters
3059                .mysql_source_timeouts
3060                .clone(),
3061            iam_auth,
3062        )?)
3063    }
3064
3065    pub async fn validate(
3066        &self,
3067        _id: CatalogItemId,
3068        storage_configuration: &StorageConfiguration,
3069    ) -> Result<MySqlConn, MySqlConnectionValidationError> {
3070        let config = self
3071            .config(
3072                &storage_configuration.connection_context.secrets_reader,
3073                storage_configuration,
3074                // We are in a normal tokio context during validation, already.
3075                InTask::No,
3076            )
3077            .await?;
3078        let mut conn = config
3079            .connect(
3080                "connection validation",
3081                &storage_configuration.connection_context.ssh_tunnel_manager,
3082            )
3083            .await?;
3084
3085        // Check if the MySQL database is configured to allow row-based consistent GTID replication
3086        let mut setting_errors = vec![];
3087        let gtid_res = mz_mysql_util::ensure_gtid_consistency(&mut conn).await;
3088        let binlog_res = mz_mysql_util::ensure_full_row_binlog_format(&mut conn).await;
3089        let order_res = mz_mysql_util::ensure_replication_commit_order(&mut conn).await;
3090        for res in [gtid_res, binlog_res, order_res] {
3091            match res {
3092                Err(MySqlError::InvalidSystemSetting {
3093                    setting,
3094                    expected,
3095                    actual,
3096                }) => {
3097                    setting_errors.push((setting, expected, actual));
3098                }
3099                Err(err) => Err(err)?,
3100                Ok(()) => {}
3101            }
3102        }
3103        if !setting_errors.is_empty() {
3104            Err(MySqlConnectionValidationError::ReplicationSettingsError(
3105                setting_errors,
3106            ))?;
3107        }
3108
3109        Ok(conn)
3110    }
3111}
3112
3113#[derive(Debug, thiserror::Error)]
3114pub enum MySqlConnectionValidationError {
3115    #[error("Invalid MySQL system replication settings")]
3116    ReplicationSettingsError(Vec<(String, String, String)>),
3117    #[error(transparent)]
3118    Client(#[from] MySqlError),
3119    #[error("{}", .0.display_with_causes())]
3120    Other(#[from] anyhow::Error),
3121}
3122
3123impl MySqlConnectionValidationError {
3124    pub fn detail(&self) -> Option<String> {
3125        match self {
3126            Self::ReplicationSettingsError(settings) => Some(format!(
3127                "Invalid MySQL system replication settings: {}",
3128                itertools::join(
3129                    settings.iter().map(|(setting, expected, actual)| format!(
3130                        "{}: expected {}, got {}",
3131                        setting, expected, actual
3132                    )),
3133                    "; "
3134                )
3135            )),
3136            _ => None,
3137        }
3138    }
3139
3140    pub fn hint(&self) -> Option<String> {
3141        match self {
3142            Self::ReplicationSettingsError(_) => {
3143                Some("Set the necessary MySQL database system settings.".into())
3144            }
3145            _ => None,
3146        }
3147    }
3148}
3149
3150impl<C: ConnectionAccess> AlterCompatible for MySqlConnection<C> {
3151    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
3152        let MySqlConnection {
3153            tunnel,
3154            // All non-tunnel options may change arbitrarily
3155            host: _,
3156            port: _,
3157            user: _,
3158            password: _,
3159            tls_mode: _,
3160            tls_root_cert: _,
3161            tls_identity: _,
3162            aws_connection: _,
3163        } = self;
3164
3165        let compatibility_checks = [(tunnel.alter_compatible(id, &other.tunnel).is_ok(), "tunnel")];
3166
3167        for (compatible, field) in compatibility_checks {
3168            if !compatible {
3169                tracing::warn!(
3170                    "MySqlConnection incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
3171                    self,
3172                    other
3173                );
3174
3175                return Err(AlterError { id });
3176            }
3177        }
3178        Ok(())
3179    }
3180}
3181
3182/// Details how to connect to an instance of Microsoft SQL Server.
3183///
3184/// For specifics of connecting to SQL Server for purposes of creating a
3185/// Materialize Source, see [`SqlServerSourceConnection`] which wraps this type.
3186///
3187/// [`SqlServerSourceConnection`]: crate::sources::SqlServerSourceConnection
3188#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3189pub struct SqlServerConnectionDetails<C: ConnectionAccess = InlinedConnection> {
3190    /// The hostname of the server.
3191    pub host: String,
3192    /// The port of the server.
3193    pub port: u16,
3194    /// Database we should connect to.
3195    pub database: String,
3196    /// The username to authenticate as.
3197    pub user: StringOrSecret,
3198    /// Password used for authentication.
3199    pub password: CatalogItemId,
3200    /// A tunnel through which to route traffic.
3201    pub tunnel: Tunnel<C>,
3202    /// Level of encryption to use for the connection.
3203    pub encryption: mz_sql_server_util::config::EncryptionLevel,
3204    /// Certificate validation policy
3205    pub certificate_validation_policy: mz_sql_server_util::config::CertificateValidationPolicy,
3206    /// TLS CA Certifiecate in PEM format
3207    pub tls_root_cert: Option<StringOrSecret>,
3208}
3209
3210impl<C: ConnectionAccess> SqlServerConnectionDetails<C> {
3211    fn validate_by_default(&self) -> bool {
3212        true
3213    }
3214}
3215
3216impl SqlServerConnectionDetails<InlinedConnection> {
3217    /// Attempts to open a connection to the upstream SQL Server instance.
3218    pub async fn validate(
3219        &self,
3220        _id: CatalogItemId,
3221        storage_configuration: &StorageConfiguration,
3222    ) -> Result<mz_sql_server_util::Client, anyhow::Error> {
3223        let config = self
3224            .resolve_config(
3225                &storage_configuration.connection_context.secrets_reader,
3226                storage_configuration,
3227                InTask::No,
3228            )
3229            .await?;
3230        tracing::debug!(?config, "Validating SQL Server connection");
3231
3232        let mut client = mz_sql_server_util::Client::connect(config).await?;
3233
3234        // Ensure the upstream SQL Server instance is configured to allow CDC.
3235        //
3236        // Run all of the checks necessary and collect the errors to provide the best
3237        // guidance as to which system settings need to be enabled.
3238        let mut replication_errors = vec![];
3239        for error in [
3240            mz_sql_server_util::inspect::ensure_database_cdc_enabled(&mut client).await,
3241            mz_sql_server_util::inspect::ensure_snapshot_isolation_enabled(&mut client).await,
3242            mz_sql_server_util::inspect::ensure_sql_server_agent_running(&mut client).await,
3243        ] {
3244            match error {
3245                Err(mz_sql_server_util::SqlServerError::InvalidSystemSetting {
3246                    name,
3247                    expected,
3248                    actual,
3249                }) => replication_errors.push((name, expected, actual)),
3250                Err(other) => Err(other)?,
3251                Ok(()) => (),
3252            }
3253        }
3254        if !replication_errors.is_empty() {
3255            Err(SqlServerConnectionValidationError::ReplicationSettingsError(replication_errors))?;
3256        }
3257
3258        Ok(client)
3259    }
3260
3261    /// Resolve all of the connection details (e.g. read from the [`SecretsReader`])
3262    /// so the returned [`Config`] can be used to open a connection with the
3263    /// upstream system.
3264    ///
3265    /// The provided [`InTask`] argument determines whether any I/O is run in an
3266    /// [`mz_ore::task`] (i.e. a different thread) or directly in the returned
3267    /// future. The main goal here is to prevent running I/O in timely threads.
3268    ///
3269    /// [`Config`]: mz_sql_server_util::Config
3270    pub async fn resolve_config(
3271        &self,
3272        secrets_reader: &Arc<dyn mz_secrets::SecretsReader>,
3273        storage_configuration: &StorageConfiguration,
3274        in_task: InTask,
3275    ) -> Result<mz_sql_server_util::Config, anyhow::Error> {
3276        let dyncfg = storage_configuration.config_set();
3277        let mut inner_config = tiberius::Config::new();
3278
3279        // Setup default connection params.
3280        inner_config.host(&self.host);
3281        inner_config.port(self.port);
3282        inner_config.database(self.database.clone());
3283        inner_config.encryption(self.encryption.into());
3284        match self.certificate_validation_policy {
3285            mz_sql_server_util::config::CertificateValidationPolicy::TrustAll => {
3286                inner_config.trust_cert()
3287            }
3288            mz_sql_server_util::config::CertificateValidationPolicy::VerifyCA => {
3289                inner_config.trust_cert_ca_pem(
3290                    self.tls_root_cert
3291                        .as_ref()
3292                        .unwrap()
3293                        .get_string(in_task, secrets_reader)
3294                        .await
3295                        .context("ca certificate")?,
3296                );
3297            }
3298            mz_sql_server_util::config::CertificateValidationPolicy::VerifySystem => (), // no-op
3299        }
3300
3301        inner_config.application_name("materialize");
3302
3303        // Read our auth settings from
3304        let user = self
3305            .user
3306            .get_string(in_task, secrets_reader)
3307            .await
3308            .context("username")?;
3309        let password = secrets_reader
3310            .read_string_in_task_if(in_task, self.password)
3311            .await
3312            .context("password")?;
3313        // TODO(sql_server3): Support other methods of authentication besides
3314        // username and password.
3315        inner_config.authentication(tiberius::AuthMethod::sql_server(user, password));
3316
3317        // Prevent users from probing our internal network ports by trying to
3318        // connect to localhost, or another non-external IP.
3319        let enforce_external_addresses = ENFORCE_EXTERNAL_ADDRESSES.get(dyncfg);
3320
3321        let tunnel = match &self.tunnel {
3322            Tunnel::Direct => {
3323                let resolved_addresses: Vec<SocketAddr> =
3324                    resolve_address(&self.host, enforce_external_addresses)
3325                        .await?
3326                        .into_iter()
3327                        .map(|ip| SocketAddr::new(ip, self.port))
3328                        .collect();
3329                mz_sql_server_util::config::TunnelConfig::Direct {
3330                    resolved_addresses: resolved_addresses.into_boxed_slice(),
3331                }
3332            }
3333            Tunnel::Ssh(SshTunnel {
3334                connection_id,
3335                connection: ssh_connection,
3336            }) => {
3337                let secret = secrets_reader
3338                    .read_in_task_if(in_task, *connection_id)
3339                    .await
3340                    .context("ssh secret")?;
3341                let key_pair = SshKeyPair::from_bytes(&secret).context("ssh key pair")?;
3342                // Ensure any SSH-bastion host we connect to is resolved to an
3343                // external address.
3344                let addresses = resolve_address(&ssh_connection.host, enforce_external_addresses)
3345                    .await
3346                    .context("ssh tunnel")?;
3347
3348                let config = SshTunnelConfig {
3349                    host: addresses.into_iter().map(|a| a.to_string()).collect(),
3350                    port: ssh_connection.port,
3351                    user: ssh_connection.user.clone(),
3352                    key_pair,
3353                };
3354                mz_sql_server_util::config::TunnelConfig::Ssh {
3355                    config,
3356                    manager: storage_configuration
3357                        .connection_context
3358                        .ssh_tunnel_manager
3359                        .clone(),
3360                    timeout: storage_configuration.parameters.ssh_timeout_config.clone(),
3361                    host: self.host.clone(),
3362                    port: self.port,
3363                }
3364            }
3365            Tunnel::AwsPrivatelink(private_link_connection) => {
3366                assert_none!(private_link_connection.port);
3367                mz_sql_server_util::config::TunnelConfig::AwsPrivatelink {
3368                    connection_id: private_link_connection.connection_id,
3369                    port: self.port,
3370                }
3371            }
3372            Tunnel::AwsPrivatelinks(_) => {
3373                unreachable!("MATCHING broker rules are only available for Kafka connections.");
3374            }
3375        };
3376
3377        Ok(mz_sql_server_util::Config::new(
3378            inner_config,
3379            tunnel,
3380            in_task,
3381        ))
3382    }
3383}
3384
3385#[derive(Debug, Clone, thiserror::Error)]
3386pub enum SqlServerConnectionValidationError {
3387    #[error("Invalid SQL Server system replication settings")]
3388    ReplicationSettingsError(Vec<(String, String, String)>),
3389}
3390
3391impl SqlServerConnectionValidationError {
3392    pub fn detail(&self) -> Option<String> {
3393        match self {
3394            Self::ReplicationSettingsError(settings) => Some(format!(
3395                "Invalid SQL Server system replication settings: {}",
3396                itertools::join(
3397                    settings.iter().map(|(setting, expected, actual)| format!(
3398                        "{}: expected {}, got {}",
3399                        setting, expected, actual
3400                    )),
3401                    "; "
3402                )
3403            )),
3404        }
3405    }
3406
3407    pub fn hint(&self) -> Option<String> {
3408        match self {
3409            _ => None,
3410        }
3411    }
3412}
3413
3414impl<R: ConnectionResolver> IntoInlineConnection<SqlServerConnectionDetails, R>
3415    for SqlServerConnectionDetails<ReferencedConnection>
3416{
3417    fn into_inline_connection(self, r: R) -> SqlServerConnectionDetails {
3418        let SqlServerConnectionDetails {
3419            host,
3420            port,
3421            database,
3422            user,
3423            password,
3424            tunnel,
3425            encryption,
3426            certificate_validation_policy,
3427            tls_root_cert,
3428        } = self;
3429
3430        SqlServerConnectionDetails {
3431            host,
3432            port,
3433            database,
3434            user,
3435            password,
3436            tunnel: tunnel.into_inline_connection(&r),
3437            encryption,
3438            certificate_validation_policy,
3439            tls_root_cert,
3440        }
3441    }
3442}
3443
3444impl<C: ConnectionAccess> AlterCompatible for SqlServerConnectionDetails<C> {
3445    fn alter_compatible(
3446        &self,
3447        id: mz_repr::GlobalId,
3448        other: &Self,
3449    ) -> Result<(), crate::controller::AlterError> {
3450        let SqlServerConnectionDetails {
3451            tunnel,
3452            // TODO(sql_server2): Figure out how these variables are allowed to change.
3453            host: _,
3454            port: _,
3455            database: _,
3456            user: _,
3457            password: _,
3458            encryption: _,
3459            certificate_validation_policy: _,
3460            tls_root_cert: _,
3461        } = self;
3462
3463        let compatibility_checks = [(tunnel.alter_compatible(id, &other.tunnel).is_ok(), "tunnel")];
3464
3465        for (compatible, field) in compatibility_checks {
3466            if !compatible {
3467                tracing::warn!(
3468                    "SqlServerConnectionDetails incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
3469                    self,
3470                    other
3471                );
3472
3473                return Err(AlterError { id });
3474            }
3475        }
3476        Ok(())
3477    }
3478}
3479
3480/// A connection to an SSH tunnel.
3481#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3482pub struct SshConnection {
3483    pub host: String,
3484    pub port: u16,
3485    pub user: String,
3486}
3487
3488use self::inline::{
3489    ConnectionAccess, ConnectionResolver, InlinedConnection, IntoInlineConnection,
3490    ReferencedConnection,
3491};
3492
3493impl AlterCompatible for SshConnection {
3494    fn alter_compatible(&self, _id: GlobalId, _other: &Self) -> Result<(), AlterError> {
3495        // Every element of the SSH connection is configurable.
3496        Ok(())
3497    }
3498}
3499
3500/// Specifies an AWS PrivateLink service for a [`Tunnel`].
3501#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3502pub struct AwsPrivatelink {
3503    /// The ID of the connection to the AWS PrivateLink service.
3504    pub connection_id: CatalogItemId,
3505    // The availability zone to use when connecting to the AWS PrivateLink service.
3506    pub availability_zone: Option<String>,
3507    /// The port to use when connecting to the AWS PrivateLink service, if
3508    /// different from the port in [`KafkaBroker::address`].
3509    pub port: Option<u16>,
3510}
3511
3512impl AlterCompatible for AwsPrivatelink {
3513    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
3514        let AwsPrivatelink {
3515            connection_id,
3516            availability_zone: _,
3517            port: _,
3518        } = self;
3519
3520        let compatibility_checks = [(connection_id == &other.connection_id, "connection_id")];
3521
3522        for (compatible, field) in compatibility_checks {
3523            if !compatible {
3524                tracing::warn!(
3525                    "AwsPrivatelink incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
3526                    self,
3527                    other
3528                );
3529
3530                return Err(AlterError { id });
3531            }
3532        }
3533
3534        Ok(())
3535    }
3536}
3537
3538#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3539pub struct AwsPrivatelinks {
3540    /// Route to brokers through PrivateLink connections according to these rules.
3541    /// Exact-match rules (no wildcards) are used as bootstrap brokers.
3542    /// Wildcard rules are applied dynamically to discovered brokers.
3543    pub rules: Vec<AwsPrivatelinkRule>,
3544}
3545
3546#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3547pub struct AwsPrivatelinkRule {
3548    /// Given a broker's host:port, should we use this route?
3549    pub pattern: ConnectionRulePattern,
3550    /// Route to the broker through this PrivateLink connection.
3551    pub to: AwsPrivatelink,
3552}
3553
3554/// Specifies an SSH tunnel connection.
3555#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3556pub struct SshTunnel<C: ConnectionAccess = InlinedConnection> {
3557    /// id of the ssh connection
3558    pub connection_id: CatalogItemId,
3559    /// ssh connection object
3560    pub connection: C::Ssh,
3561}
3562
3563impl<R: ConnectionResolver> IntoInlineConnection<SshTunnel, R> for SshTunnel<ReferencedConnection> {
3564    fn into_inline_connection(self, r: R) -> SshTunnel {
3565        let SshTunnel {
3566            connection,
3567            connection_id,
3568        } = self;
3569
3570        SshTunnel {
3571            connection: r.resolve_connection(connection).unwrap_ssh(),
3572            connection_id,
3573        }
3574    }
3575}
3576
3577impl SshTunnel<InlinedConnection> {
3578    /// Like [`SshTunnelConfig::connect`], but the SSH key is loaded from a
3579    /// secret.
3580    async fn connect(
3581        &self,
3582        storage_configuration: &StorageConfiguration,
3583        remote_host: &str,
3584        remote_port: u16,
3585        in_task: InTask,
3586    ) -> Result<ManagedSshTunnelHandle, anyhow::Error> {
3587        // Ensure any ssh-bastion host we connect to is resolved to an external address.
3588        let resolved = resolve_address(
3589            &self.connection.host,
3590            ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
3591        )
3592        .await?;
3593        storage_configuration
3594            .connection_context
3595            .ssh_tunnel_manager
3596            .connect(
3597                SshTunnelConfig {
3598                    host: resolved
3599                        .iter()
3600                        .map(|a| a.to_string())
3601                        .collect::<BTreeSet<_>>(),
3602                    port: self.connection.port,
3603                    user: self.connection.user.clone(),
3604                    key_pair: SshKeyPair::from_bytes(
3605                        &storage_configuration
3606                            .connection_context
3607                            .secrets_reader
3608                            .read_in_task_if(in_task, self.connection_id)
3609                            .await?,
3610                    )?,
3611                },
3612                remote_host,
3613                remote_port,
3614                storage_configuration.parameters.ssh_timeout_config,
3615                in_task,
3616            )
3617            .await
3618    }
3619}
3620
3621impl<C: ConnectionAccess> AlterCompatible for SshTunnel<C> {
3622    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
3623        let SshTunnel {
3624            connection_id,
3625            connection,
3626        } = self;
3627
3628        let compatibility_checks = [
3629            (connection_id == &other.connection_id, "connection_id"),
3630            (
3631                connection.alter_compatible(id, &other.connection).is_ok(),
3632                "connection",
3633            ),
3634        ];
3635
3636        for (compatible, field) in compatibility_checks {
3637            if !compatible {
3638                tracing::warn!(
3639                    "SshTunnel incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
3640                    self,
3641                    other
3642                );
3643
3644                return Err(AlterError { id });
3645            }
3646        }
3647
3648        Ok(())
3649    }
3650}
3651
3652impl SshConnection {
3653    #[allow(clippy::unused_async)]
3654    async fn validate(
3655        &self,
3656        id: CatalogItemId,
3657        storage_configuration: &StorageConfiguration,
3658    ) -> Result<(), anyhow::Error> {
3659        let secret = storage_configuration
3660            .connection_context
3661            .secrets_reader
3662            .read_in_task_if(
3663                // We are in a normal tokio context during validation, already.
3664                InTask::No,
3665                id,
3666            )
3667            .await?;
3668        let key_pair = SshKeyPair::from_bytes(&secret)?;
3669
3670        // Ensure any ssh-bastion host we connect to is resolved to an external address.
3671        let resolved = resolve_address(
3672            &self.host,
3673            ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
3674        )
3675        .await?;
3676
3677        let config = SshTunnelConfig {
3678            host: resolved
3679                .iter()
3680                .map(|a| a.to_string())
3681                .collect::<BTreeSet<_>>(),
3682            port: self.port,
3683            user: self.user.clone(),
3684            key_pair,
3685        };
3686        // Note that we do NOT use the `SshTunnelManager` here, as we want to validate that we
3687        // can actually create a new connection to the ssh bastion, without tunneling.
3688        config
3689            .validate(storage_configuration.parameters.ssh_timeout_config)
3690            .await
3691    }
3692
3693    fn validate_by_default(&self) -> bool {
3694        false
3695    }
3696}
3697
3698impl AwsPrivatelinkConnection {
3699    #[allow(clippy::unused_async)]
3700    async fn validate(
3701        &self,
3702        id: CatalogItemId,
3703        storage_configuration: &StorageConfiguration,
3704    ) -> Result<(), ConnectionValidationError> {
3705        // An endpoint for an unusable service name reports a misleading
3706        // condition (missing availability zones), so check the name first.
3707        Self::check_service_name(&self.service_name)?;
3708
3709        let Some(ref cloud_resource_reader) = storage_configuration
3710            .connection_context
3711            .cloud_resource_reader
3712        else {
3713            return Err(anyhow!("AWS PrivateLink connections are unsupported").into());
3714        };
3715
3716        // No need to optionally run this in a task, as we are just validating from envd.
3717        let status = cloud_resource_reader.read(id).await?;
3718
3719        let availability = status
3720            .conditions
3721            .as_ref()
3722            .and_then(|conditions| conditions.iter().find(|c| c.type_ == "Available"));
3723
3724        match availability {
3725            Some(condition) if condition.status == "True" => Ok(()),
3726            Some(condition) => Err(anyhow!("{}", condition.message).into()),
3727            None => Err(anyhow!("Endpoint availability is unknown").into()),
3728        }
3729    }
3730
3731    fn validate_by_default(&self) -> bool {
3732        false
3733    }
3734}
3735
3736#[cfg(test)]
3737mod tests {
3738    use super::*;
3739
3740    #[mz_ore::test]
3741    fn test_catalog_headers() {
3742        let props = BTreeMap::from_iter(
3743            [
3744                (REST_CATALOG_PROP_URI, "https://catalog.example"),
3745                (REST_CATALOG_PROP_WAREHOUSE, "wh"),
3746                ("header.x-goog-user-project", "some-project"),
3747                (REST_CATALOG_PROP_ACCESS_DELEGATION, "vended-credentials"),
3748            ]
3749            .map(|(k, v)| (k.to_string(), v.to_string())),
3750        );
3751
3752        // Only `header.*` props become headers, and the prefix is stripped. Header names are
3753        // matched case-insensitively, so the delegation prop's mixed-case spelling still lands.
3754        let headers = IcebergCatalogConnection::catalog_headers(&props).expect("valid headers");
3755        assert_eq!(headers.len(), 2);
3756        assert_eq!(headers["x-goog-user-project"], "some-project");
3757        assert_eq!(headers["x-iceberg-access-delegation"], "vended-credentials");
3758
3759        // A prop whose name is not a legal header is an error rather than a dropped header: it
3760        // would otherwise mean silently talking to the catalog differently than asked.
3761        let props = BTreeMap::from([("header.bad name".to_string(), "v".to_string())]);
3762        assert!(IcebergCatalogConnection::catalog_headers(&props).is_err());
3763    }
3764
3765    #[mz_ore::test]
3766    fn test_check_service_name() {
3767        // Customer-owned and AWS-managed endpoint services are both accepted,
3768        // as is anything else that could be an endpoint service name.
3769        for name in [
3770            "com.amazonaws.vpce.us-east-1.vpce-svc-0e123abc123198abc",
3771            "com.amazonaws.vpce.test.vpce-svc-e2e-test",
3772            "com.amazonaws.us-east-1.s3",
3773            "com.amazonaws.anything",
3774        ] {
3775            assert_eq!(
3776                AwsPrivatelinkConnection::check_service_name(name),
3777                Ok(()),
3778                "expected {name} to be accepted"
3779            );
3780        }
3781
3782        for name in [
3783            "",
3784            "com.amazonaws",
3785            "vpce-svc-0e123abc123198abc",
3786            "my-db-lb-0123456789abcdef.elb.eu-central-1.amazonaws.com",
3787            "db.internal.example.org",
3788        ] {
3789            let err = AwsPrivatelinkConnection::check_service_name(name)
3790                .expect_err("service name should be rejected");
3791            assert_eq!(err.name, name);
3792        }
3793    }
3794}