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            } else if let Ok(ca_file) = std::env::var("SSL_CERT_FILE") {
1742                // librdkafka ignores `SSL_CERT_FILE` when it finds a CA bundle
1743                // at one of its built-in paths, which would skip the bundle
1744                // `--additional-trust-bundle` installs. Setting the location
1745                // alongside `ssl.ca.pem` would make a connection's own CA add
1746                // to these CAs instead of replacing them.
1747                options.insert("ssl.ca.location".into(), ca_file.into());
1748            }
1749            if let Some(identity) = &tls.identity {
1750                options.insert("ssl.key.pem".into(), StringOrSecret::Secret(identity.key));
1751                options.insert("ssl.certificate.pem".into(), identity.cert.clone());
1752            }
1753        }
1754        if let Some(sasl) = &self.sasl {
1755            options.insert("sasl.mechanisms".into(), (&sasl.mechanism).into());
1756            options.insert("sasl.username".into(), sasl.username.clone());
1757            if let Some(password) = sasl.password {
1758                options.insert("sasl.password".into(), StringOrSecret::Secret(password));
1759            }
1760        }
1761
1762        options.insert(
1763            "retry.backoff.ms".into(),
1764            KAFKA_RETRY_BACKOFF
1765                .get(storage_configuration.config_set())
1766                .as_millis()
1767                .into(),
1768        );
1769        options.insert(
1770            "retry.backoff.max.ms".into(),
1771            KAFKA_RETRY_BACKOFF_MAX
1772                .get(storage_configuration.config_set())
1773                .as_millis()
1774                .into(),
1775        );
1776        options.insert(
1777            "reconnect.backoff.ms".into(),
1778            KAFKA_RECONNECT_BACKOFF
1779                .get(storage_configuration.config_set())
1780                .as_millis()
1781                .into(),
1782        );
1783        options.insert(
1784            "reconnect.backoff.max.ms".into(),
1785            KAFKA_RECONNECT_BACKOFF_MAX
1786                .get(storage_configuration.config_set())
1787                .as_millis()
1788                .into(),
1789        );
1790
1791        let mut config = mz_kafka_util::client::create_new_client_config(
1792            storage_configuration
1793                .connection_context
1794                .librdkafka_log_level,
1795            storage_configuration.parameters.kafka_timeout_config,
1796        );
1797        for (k, v) in options {
1798            config.set(
1799                k,
1800                v.get_string(
1801                    in_task,
1802                    &storage_configuration.connection_context.secrets_reader,
1803                )
1804                .await
1805                .context("reading kafka secret")?,
1806            );
1807        }
1808        for (k, v) in extra_options {
1809            config.set(*k, v);
1810        }
1811
1812        let aws_config = match self.sasl.as_ref().and_then(|sasl| sasl.aws.as_ref()) {
1813            None => None,
1814            Some(aws) => Some(
1815                aws.connection
1816                    .load_sdk_config(
1817                        &storage_configuration.connection_context,
1818                        aws.connection_id,
1819                        in_task,
1820                        ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
1821                    )
1822                    .await?,
1823            ),
1824        };
1825
1826        let mut context = TunnelingClientContext::new(
1827            context,
1828            Handle::current(),
1829            storage_configuration
1830                .connection_context
1831                .ssh_tunnel_manager
1832                .clone(),
1833            storage_configuration.parameters.ssh_timeout_config,
1834            aws_config,
1835            in_task,
1836            ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
1837        );
1838
1839        match &self.default_tunnel {
1840            Tunnel::Direct => {
1841                // By default, don't offer a default override for broker address lookup.
1842            }
1843            Tunnel::AwsPrivatelink(pl) => {
1844                context.set_default_tunnel(TunnelConfig::StaticHost(
1845                    // Possible bug: We have been ignoring the configured port.
1846                    KafkaConnection::from_default_aws_privatelink(pl).host,
1847                ));
1848            }
1849            Tunnel::AwsPrivatelinks(pl) => {
1850                context.set_default_tunnel(TunnelConfig::Rules(
1851                    KafkaConnection::from_aws_privatelinks(pl),
1852                ));
1853            }
1854            Tunnel::Ssh(ssh_tunnel) => {
1855                let secret = storage_configuration
1856                    .connection_context
1857                    .secrets_reader
1858                    .read_in_task_if(in_task, ssh_tunnel.connection_id)
1859                    .await?;
1860                let key_pair = SshKeyPair::from_bytes(&secret)?;
1861
1862                // Ensure any ssh-bastion address we connect to is resolved to an external address.
1863                let resolved = resolve_address(
1864                    &ssh_tunnel.connection.host,
1865                    ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
1866                )
1867                .await?;
1868                context.set_default_tunnel(TunnelConfig::Ssh(SshTunnelConfig {
1869                    host: resolved
1870                        .iter()
1871                        .map(|a| a.to_string())
1872                        .collect::<BTreeSet<_>>(),
1873                    port: ssh_tunnel.connection.port,
1874                    user: ssh_tunnel.connection.user.clone(),
1875                    key_pair,
1876                }));
1877            }
1878        }
1879        info!(
1880            "kafka: tunnel config set to {}",
1881            match &self.default_tunnel {
1882                Tunnel::Direct => "Direct".to_string(),
1883                Tunnel::AwsPrivatelink(_) => "AwsPrivatelink (static host)".to_string(),
1884                Tunnel::AwsPrivatelinks(pl) =>
1885                    format!("AwsPrivatelinks ({} rules)", pl.rules.len()),
1886                Tunnel::Ssh(_) => "Ssh".to_string(),
1887            }
1888        );
1889
1890        // Here, we preemptively rewrite broker addresses.
1891        // In concept, this overlaps with 'TunnelingClientContext::resolve_broker_addr'.
1892        for broker in &self.brokers {
1893            let mut addr_parts = broker.address.splitn(2, ':');
1894            let addr = BrokerAddr {
1895                host: addr_parts
1896                    .next()
1897                    .context("BROKER is not address:port")?
1898                    .into(),
1899                port: addr_parts
1900                    .next()
1901                    .unwrap_or("9092")
1902                    .parse()
1903                    .context("parsing BROKER port")?,
1904            };
1905            match &broker.tunnel {
1906                Tunnel::Direct => {
1907                    // By default, don't override broker address lookup.
1908                    //
1909                    // N.B.
1910                    //
1911                    // We _could_ pre-setup the default ssh tunnel for all known brokers here, but
1912                    // we avoid doing because:
1913                    // - Its not necessary.
1914                    // - Not doing so makes it easier to test the `FailedDefaultSshTunnel` path
1915                    // in the `TunnelingClientContext`.
1916                }
1917                Tunnel::AwsPrivatelink(aws_privatelink) => {
1918                    context.add_broker_rewrite(
1919                        addr,
1920                        KafkaConnection::from_aws_privatelink(aws_privatelink),
1921                    );
1922                }
1923                Tunnel::AwsPrivatelinks(_) => unreachable!(
1924                    "Individually predefined brokers do not use rule-based PrivateLinks routing."
1925                ),
1926                Tunnel::Ssh(ssh_tunnel) => {
1927                    // Ensure any SSH bastion address we connect to is resolved to an external address.
1928                    let ssh_host_resolved = resolve_address(
1929                        &ssh_tunnel.connection.host,
1930                        ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
1931                    )
1932                    .await?;
1933                    context
1934                        .add_ssh_tunnel(
1935                            addr,
1936                            SshTunnelConfig {
1937                                host: ssh_host_resolved
1938                                    .iter()
1939                                    .map(|a| a.to_string())
1940                                    .collect::<BTreeSet<_>>(),
1941                                port: ssh_tunnel.connection.port,
1942                                user: ssh_tunnel.connection.user.clone(),
1943                                key_pair: SshKeyPair::from_bytes(
1944                                    &storage_configuration
1945                                        .connection_context
1946                                        .secrets_reader
1947                                        .read_in_task_if(in_task, ssh_tunnel.connection_id)
1948                                        .await?,
1949                                )?,
1950                            },
1951                        )
1952                        .await
1953                        .map_err(ContextCreationError::Ssh)?;
1954                }
1955            }
1956        }
1957
1958        Ok(mz_kafka_util::client::create_with_context(
1959            &config, context,
1960        )?)
1961    }
1962
1963    async fn validate(
1964        &self,
1965        _id: CatalogItemId,
1966        storage_configuration: &StorageConfiguration,
1967    ) -> Result<(), anyhow::Error> {
1968        let (context, error_rx) = MzClientContext::with_errors();
1969        let consumer: BaseConsumer<_> = self
1970            .create_with_context(
1971                storage_configuration,
1972                context,
1973                &BTreeMap::new(),
1974                // We are in a normal tokio context during validation, already.
1975                InTask::No,
1976            )
1977            .await?;
1978        let consumer = Arc::new(consumer);
1979
1980        let timeout = storage_configuration
1981            .parameters
1982            .kafka_timeout_config
1983            .fetch_metadata_timeout;
1984
1985        // librdkafka doesn't expose an API for determining whether a connection to
1986        // the Kafka cluster has been successfully established. So we make a
1987        // metadata request, though we don't care about the results, so that we can
1988        // report any errors making that request. If the request succeeds, we know
1989        // we were able to contact at least one broker, and that's a good proxy for
1990        // being able to contact all the brokers in the cluster.
1991        //
1992        // The downside of this approach is it produces a generic error message like
1993        // "metadata fetch error" with no additional details. The real networking
1994        // error is buried in the librdkafka logs, which are not visible to users.
1995        info!("kafka: starting connection validation via fetch_metadata (timeout={timeout:?})");
1996        let result = mz_ore::task::spawn_blocking(|| "kafka_get_metadata", {
1997            let consumer = Arc::clone(&consumer);
1998            move || consumer.fetch_metadata(None, timeout)
1999        })
2000        .await;
2001        info!(
2002            "kafka: connection validation result: {}",
2003            if result.is_ok() { "success" } else { "failed" },
2004        );
2005        match result {
2006            Ok(_) => Ok(()),
2007            // The error returned by `fetch_metadata` does not provide any details which makes for
2008            // a crappy user facing error message. For this reason we attempt to grab a better
2009            // error message from the client context, which should contain any error logs emitted
2010            // by librdkafka, and fallback to the generic error if there is nothing there.
2011            Err(err) => {
2012                // Multiple errors might have been logged during this validation but some are more
2013                // relevant than others. Specifically, we prefer non-internal errors over internal
2014                // errors since those give much more useful information to the users.
2015                let main_err = error_rx.try_iter().reduce(|cur, new| match cur {
2016                    MzKafkaError::Internal(_) => new,
2017                    _ => cur,
2018                });
2019
2020                // Don't drop the consumer until after we've drained the errors
2021                // channel. Dropping the consumer can introduce spurious errors.
2022                // See database-issues#7432.
2023                drop(consumer);
2024
2025                match main_err {
2026                    Some(err) => Err(err.into()),
2027                    None => Err(err.into()),
2028                }
2029            }
2030        }
2031    }
2032
2033    /// The "default" PrivateLink connection is used for bootstrapping Kafka.
2034    fn from_default_aws_privatelink(pl: &AwsPrivatelink) -> BrokerRewrite {
2035        BrokerRewrite {
2036            host: vpc_endpoint_host(
2037                pl.connection_id,
2038                None, // Default tunnel does not support availability zones.
2039            ),
2040            port: pl.port,
2041        }
2042    }
2043
2044    /// The "not default" PrivateLink connections are used for routing to specific Kafka brokers.
2045    fn from_aws_privatelink(pl: &AwsPrivatelink) -> BrokerRewrite {
2046        BrokerRewrite {
2047            host: vpc_endpoint_host(pl.connection_id, pl.availability_zone.as_deref()),
2048            port: pl.port,
2049        }
2050    }
2051
2052    fn from_aws_privatelink_rule(
2053        AwsPrivatelinkRule { pattern, to }: &AwsPrivatelinkRule,
2054    ) -> (mz_kafka_util::client::ConnectionRulePattern, BrokerRewrite) {
2055        (
2056            mz_kafka_util::client::ConnectionRulePattern {
2057                prefix_wildcard: pattern.prefix_wildcard,
2058                literal_match: pattern.literal_match.clone(),
2059                suffix_wildcard: pattern.suffix_wildcard,
2060            },
2061            KafkaConnection::from_aws_privatelink(to),
2062        )
2063    }
2064
2065    fn from_aws_privatelinks(pl: &AwsPrivatelinks) -> HostMappingRules {
2066        HostMappingRules {
2067            rules: pl
2068                .rules
2069                .iter()
2070                .map(KafkaConnection::from_aws_privatelink_rule)
2071                .collect_vec(),
2072        }
2073    }
2074}
2075
2076impl<C: ConnectionAccess> AlterCompatible for KafkaConnection<C> {
2077    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
2078        let KafkaConnection {
2079            brokers: _,
2080            default_tunnel: _,
2081            progress_topic,
2082            progress_topic_options,
2083            options: _,
2084            tls: _,
2085            sasl: _,
2086        } = self;
2087
2088        let compatibility_checks = [
2089            (progress_topic == &other.progress_topic, "progress_topic"),
2090            (
2091                progress_topic_options == &other.progress_topic_options,
2092                "progress_topic_options",
2093            ),
2094        ];
2095
2096        for (compatible, field) in compatibility_checks {
2097            if !compatible {
2098                tracing::warn!(
2099                    "KafkaConnection incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
2100                    self,
2101                    other
2102                );
2103
2104                return Err(AlterError { id });
2105            }
2106        }
2107
2108        Ok(())
2109    }
2110}
2111
2112/// A connection to a Confluent Schema Registry.
2113#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2114pub struct CsrConnection<C: ConnectionAccess = InlinedConnection> {
2115    /// The URL of the schema registry.
2116    pub url: Url,
2117    /// Trusted root TLS certificate in PEM format.
2118    pub tls_root_cert: Option<StringOrSecret>,
2119    /// An optional TLS client certificate for authentication with the schema
2120    /// registry.
2121    pub tls_identity: Option<TlsIdentity>,
2122    /// Optional HTTP authentication credentials for the schema registry.
2123    pub http_auth: Option<CsrConnectionHttpAuth>,
2124    /// A tunnel through which to route traffic.
2125    pub tunnel: Tunnel<C>,
2126}
2127
2128impl<R: ConnectionResolver> IntoInlineConnection<CsrConnection, R>
2129    for CsrConnection<ReferencedConnection>
2130{
2131    fn into_inline_connection(self, r: R) -> CsrConnection {
2132        let CsrConnection {
2133            url,
2134            tls_root_cert,
2135            tls_identity,
2136            http_auth,
2137            tunnel,
2138        } = self;
2139        CsrConnection {
2140            url,
2141            tls_root_cert,
2142            tls_identity,
2143            http_auth,
2144            tunnel: tunnel.into_inline_connection(r),
2145        }
2146    }
2147}
2148
2149impl<C: ConnectionAccess> CsrConnection<C> {
2150    fn validate_by_default(&self) -> bool {
2151        true
2152    }
2153}
2154
2155impl CsrConnection {
2156    /// Constructs a schema registry client from the connection.
2157    pub async fn connect(
2158        &self,
2159        storage_configuration: &StorageConfiguration,
2160        in_task: InTask,
2161    ) -> Result<mz_ccsr::Client, CsrConnectError> {
2162        let mut client_config = mz_ccsr::ClientConfig::new(self.url.clone());
2163        if let Some(root_cert) = &self.tls_root_cert {
2164            let root_cert = root_cert
2165                .get_string(
2166                    in_task,
2167                    &storage_configuration.connection_context.secrets_reader,
2168                )
2169                .await?;
2170            let root_cert = Certificate::from_pem(root_cert.as_bytes())?;
2171            client_config = client_config.add_root_certificate(root_cert);
2172        }
2173
2174        if let Some(tls_identity) = &self.tls_identity {
2175            let key = &storage_configuration
2176                .connection_context
2177                .secrets_reader
2178                .read_string_in_task_if(in_task, tls_identity.key)
2179                .await?;
2180            let cert = tls_identity
2181                .cert
2182                .get_string(
2183                    in_task,
2184                    &storage_configuration.connection_context.secrets_reader,
2185                )
2186                .await?;
2187            let ident = Identity::from_pem(key.as_bytes(), cert.as_bytes())?;
2188            client_config = client_config.identity(ident);
2189        }
2190
2191        if let Some(http_auth) = &self.http_auth {
2192            let username = http_auth
2193                .username
2194                .get_string(
2195                    in_task,
2196                    &storage_configuration.connection_context.secrets_reader,
2197                )
2198                .await?;
2199            let password = match http_auth.password {
2200                None => None,
2201                Some(password) => Some(
2202                    storage_configuration
2203                        .connection_context
2204                        .secrets_reader
2205                        .read_string_in_task_if(in_task, password)
2206                        .await?,
2207                ),
2208            };
2209            client_config = client_config.auth(username, password);
2210        }
2211
2212        // TODO: use types to enforce that the URL has a string hostname.
2213        let host = self
2214            .url
2215            .host_str()
2216            .ok_or_else(|| anyhow!("url missing host"))?;
2217        match &self.tunnel {
2218            Tunnel::Direct => {
2219                // Ensure any host we connect to is resolved to an external address.
2220                let resolved = resolve_address(
2221                    host,
2222                    ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
2223                )
2224                .await?;
2225                client_config = client_config.resolve_to_addrs(
2226                    host,
2227                    &resolved
2228                        .iter()
2229                        .map(|addr| SocketAddr::new(*addr, 0))
2230                        .collect::<Vec<_>>(),
2231                )
2232            }
2233            Tunnel::Ssh(ssh_tunnel) => {
2234                let ssh_tunnel = ssh_tunnel
2235                    .connect(
2236                        storage_configuration,
2237                        host,
2238                        // Honor the URL scheme's default port (443 for https,
2239                        // 80 for http) if no explicit port was provided.
2240                        self.url.port_or_known_default().unwrap_or(80),
2241                        in_task,
2242                    )
2243                    .await
2244                    .map_err(CsrConnectError::Ssh)?;
2245
2246                // Carefully inject the SSH tunnel into the client
2247                // configuration. This is delicate because we need TLS
2248                // verification to continue to use the remote hostname rather
2249                // than the tunnel hostname.
2250
2251                client_config = client_config
2252                    // `resolve_to_addrs` allows us to rewrite the hostname
2253                    // at the DNS level, which means the TCP connection is
2254                    // correctly routed through the tunnel, but TLS verification
2255                    // is still performed against the remote hostname.
2256                    // Unfortunately the port here is ignored if the URL also
2257                    // specifies a port...
2258                    .resolve_to_addrs(host, &[SocketAddr::new(ssh_tunnel.local_addr().ip(), 0)])
2259                    // ...so we also dynamically rewrite the URL to use the
2260                    // current port for the SSH tunnel.
2261                    //
2262                    // WARNING: this is brittle, because we only dynamically
2263                    // update the client configuration with the tunnel *port*,
2264                    // and not the hostname This works fine in practice, because
2265                    // only the SSH tunnel port will change if the tunnel fails
2266                    // and has to be restarted (the hostname is always
2267                    // 127.0.0.1)--but this is an an implementation detail of
2268                    // the SSH tunnel code that we're relying on.
2269                    .dynamic_url({
2270                        let remote_url = self.url.clone();
2271                        move || {
2272                            let mut url = remote_url.clone();
2273                            url.set_port(Some(ssh_tunnel.local_addr().port()))
2274                                .expect("cannot fail");
2275                            url
2276                        }
2277                    });
2278            }
2279            Tunnel::AwsPrivatelink(connection) => {
2280                assert_none!(connection.port);
2281
2282                let privatelink_host = mz_cloud_resources::vpc_endpoint_host(
2283                    connection.connection_id,
2284                    connection.availability_zone.as_deref(),
2285                );
2286                let addrs: Vec<_> = net::lookup_host((privatelink_host, 0))
2287                    .await
2288                    .context("resolving PrivateLink host")?
2289                    .collect();
2290                client_config = client_config.resolve_to_addrs(host, &addrs)
2291            }
2292            Tunnel::AwsPrivatelinks(_) => {
2293                unreachable!("MATCHING broker rules are only available for Kafka connections.");
2294            }
2295        }
2296
2297        Ok(client_config.build()?)
2298    }
2299
2300    async fn validate(
2301        &self,
2302        _id: CatalogItemId,
2303        storage_configuration: &StorageConfiguration,
2304    ) -> Result<(), anyhow::Error> {
2305        let client = self
2306            .connect(
2307                storage_configuration,
2308                // We are in a normal tokio context during validation, already.
2309                InTask::No,
2310            )
2311            .await?;
2312        client.list_subjects().await?;
2313        Ok(())
2314    }
2315}
2316
2317impl<C: ConnectionAccess> AlterCompatible for CsrConnection<C> {
2318    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
2319        let CsrConnection {
2320            tunnel,
2321            // All non-tunnel fields may change
2322            url: _,
2323            tls_root_cert: _,
2324            tls_identity: _,
2325            http_auth: _,
2326        } = self;
2327
2328        let compatibility_checks = [(tunnel.alter_compatible(id, &other.tunnel).is_ok(), "tunnel")];
2329
2330        for (compatible, field) in compatibility_checks {
2331            if !compatible {
2332                tracing::warn!(
2333                    "CsrConnection incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
2334                    self,
2335                    other
2336                );
2337
2338                return Err(AlterError { id });
2339            }
2340        }
2341        Ok(())
2342    }
2343}
2344
2345/// A connection to an AWS Glue Schema Registry.
2346///
2347/// AWS credentials, region, and endpoint are inherited from the referenced
2348/// [`AwsConnection`]; this struct only carries the per-registry settings.
2349#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2350pub struct GlueSchemaRegistryConnection<C: ConnectionAccess = InlinedConnection> {
2351    /// The referenced AWS connection that supplies credentials, region, and
2352    /// (optional) endpoint.
2353    pub aws_connection: AwsConnectionReference<C>,
2354    /// The Glue Schema Registry name within the AWS account/region.
2355    pub registry_name: String,
2356}
2357
2358impl<R: ConnectionResolver> IntoInlineConnection<GlueSchemaRegistryConnection, R>
2359    for GlueSchemaRegistryConnection<ReferencedConnection>
2360{
2361    fn into_inline_connection(self, r: R) -> GlueSchemaRegistryConnection {
2362        let GlueSchemaRegistryConnection {
2363            aws_connection,
2364            registry_name,
2365        } = self;
2366        GlueSchemaRegistryConnection {
2367            aws_connection: aws_connection.into_inline_connection(&r),
2368            registry_name,
2369        }
2370    }
2371}
2372
2373impl<C: ConnectionAccess> GlueSchemaRegistryConnection<C> {
2374    fn validate_by_default(&self) -> bool {
2375        // Matches CSR: default-validate so a bad registry name fails at
2376        // `CREATE CONNECTION` rather than surfacing later on first use.
2377        // Users can still opt out with `WITH (VALIDATE = false)`.
2378        true
2379    }
2380}
2381
2382impl GlueSchemaRegistryConnection {
2383    async fn validate(
2384        &self,
2385        _id: CatalogItemId,
2386        storage_configuration: &StorageConfiguration,
2387    ) -> Result<(), anyhow::Error> {
2388        let enforce_external_addresses =
2389            crate::dyncfgs::ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set());
2390        let sdk_config = self
2391            .aws_connection
2392            .connection
2393            .load_sdk_config(
2394                &storage_configuration.connection_context,
2395                self.aws_connection.connection_id,
2396                // We are in a normal tokio context during validation.
2397                InTask::No,
2398                enforce_external_addresses,
2399            )
2400            .await?;
2401        let client = mz_aws_glue_schema_registry::ClientConfig::new(sdk_config).build();
2402        match client.get_registry(&self.registry_name).await {
2403            Ok(_) => Ok(()),
2404            Err(mz_aws_glue_schema_registry::GetRegistryError::NotFound) => Err(anyhow!(
2405                "AWS Glue Schema Registry {:?} does not exist in the configured account/region",
2406                self.registry_name
2407            )),
2408            Err(err) => Err(anyhow::Error::new(err).context(format!(
2409                "failed to validate AWS Glue Schema Registry connection (registry={:?})",
2410                self.registry_name
2411            ))),
2412        }
2413    }
2414}
2415
2416impl<C: ConnectionAccess> AlterCompatible for GlueSchemaRegistryConnection<C> {
2417    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
2418        let GlueSchemaRegistryConnection {
2419            registry_name,
2420            // The referenced AWS connection itself may be swapped; matches
2421            // the permissive policy of MySqlConnection / SqlServerConnection.
2422            aws_connection: _,
2423        } = self;
2424
2425        let compatibility_checks = [(registry_name == &other.registry_name, "registry_name")];
2426
2427        for (compatible, field) in compatibility_checks {
2428            if !compatible {
2429                tracing::warn!(
2430                    "GlueSchemaRegistryConnection incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
2431                    self,
2432                    other
2433                );
2434
2435                return Err(AlterError { id });
2436            }
2437        }
2438        Ok(())
2439    }
2440}
2441
2442/// A TLS key pair used for client identity.
2443#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2444pub struct TlsIdentity {
2445    /// The client's TLS public certificate in PEM format.
2446    pub cert: StringOrSecret,
2447    /// The ID of the secret containing the client's TLS private key in PEM
2448    /// format.
2449    pub key: CatalogItemId,
2450}
2451
2452/// HTTP authentication credentials in a [`CsrConnection`].
2453#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2454pub struct CsrConnectionHttpAuth {
2455    /// The username.
2456    pub username: StringOrSecret,
2457    /// The ID of the secret containing the password, if any.
2458    pub password: Option<CatalogItemId>,
2459}
2460
2461/// A connection to a PostgreSQL server.
2462#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2463pub struct PostgresConnection<C: ConnectionAccess = InlinedConnection> {
2464    /// The hostname of the server.
2465    pub host: String,
2466    /// The port of the server.
2467    pub port: u16,
2468    /// The name of the database to connect to.
2469    pub database: String,
2470    /// The username to authenticate as.
2471    pub user: StringOrSecret,
2472    /// An optional password for authentication.
2473    pub password: Option<CatalogItemId>,
2474    /// A tunnel through which to route traffic.
2475    pub tunnel: Tunnel<C>,
2476    /// Whether to use TLS for encryption, authentication, or both.
2477    pub tls_mode: SslMode,
2478    /// An optional root TLS certificate in PEM format, to verify the server's
2479    /// identity.
2480    pub tls_root_cert: Option<StringOrSecret>,
2481    /// An optional TLS client certificate for authentication.
2482    pub tls_identity: Option<TlsIdentity>,
2483    /// Reference to the AWS connection to use for IAM authentication with
2484    /// Amazon RDS or Aurora, in place of a password.
2485    pub aws_connection: Option<AwsConnectionReference<C>>,
2486}
2487
2488impl<R: ConnectionResolver> IntoInlineConnection<PostgresConnection, R>
2489    for PostgresConnection<ReferencedConnection>
2490{
2491    fn into_inline_connection(self, r: R) -> PostgresConnection {
2492        let PostgresConnection {
2493            host,
2494            port,
2495            database,
2496            user,
2497            password,
2498            tunnel,
2499            tls_mode,
2500            tls_root_cert,
2501            tls_identity,
2502            aws_connection,
2503        } = self;
2504
2505        PostgresConnection {
2506            host,
2507            port,
2508            database,
2509            user,
2510            password,
2511            tunnel: tunnel.into_inline_connection(&r),
2512            tls_mode,
2513            tls_root_cert,
2514            tls_identity,
2515            aws_connection: aws_connection.map(|aws| aws.into_inline_connection(&r)),
2516        }
2517    }
2518}
2519
2520impl<C: ConnectionAccess> PostgresConnection<C> {
2521    fn validate_by_default(&self) -> bool {
2522        true
2523    }
2524}
2525
2526impl PostgresConnection<InlinedConnection> {
2527    pub async fn config(
2528        &self,
2529        secrets_reader: &Arc<dyn mz_secrets::SecretsReader>,
2530        storage_configuration: &StorageConfiguration,
2531        in_task: InTask,
2532    ) -> Result<mz_postgres_util::Config, anyhow::Error> {
2533        let params = &storage_configuration.parameters;
2534
2535        let mut config = tokio_postgres::Config::new();
2536        config
2537            .host(&self.host)
2538            .port(self.port)
2539            .dbname(&self.database)
2540            .user(&self.user.get_string(in_task, secrets_reader).await?)
2541            .ssl_mode(self.tls_mode)
2542            .application_name("materialize");
2543        if let Some(password) = self.password {
2544            let password = secrets_reader
2545                .read_string_in_task_if(in_task, password)
2546                .await?;
2547            config.password(password);
2548        }
2549        if let Some(tls_root_cert) = &self.tls_root_cert {
2550            let tls_root_cert = tls_root_cert.get_string(in_task, secrets_reader).await?;
2551            config.ssl_root_cert(tls_root_cert.as_bytes());
2552        }
2553        if let Some(tls_identity) = &self.tls_identity {
2554            let cert = tls_identity
2555                .cert
2556                .get_string(in_task, secrets_reader)
2557                .await?;
2558            let key = secrets_reader
2559                .read_string_in_task_if(in_task, tls_identity.key)
2560                .await?;
2561            config.ssl_cert(cert.as_bytes()).ssl_key(key.as_bytes());
2562        }
2563
2564        if let Some(connect_timeout) = params.pg_source_connect_timeout {
2565            config.connect_timeout(connect_timeout);
2566        }
2567        if let Some(keepalives_retries) = params.pg_source_tcp_keepalives_retries {
2568            config.keepalives_retries(keepalives_retries);
2569        }
2570        if let Some(keepalives_idle) = params.pg_source_tcp_keepalives_idle {
2571            config.keepalives_idle(keepalives_idle);
2572        }
2573        if let Some(keepalives_interval) = params.pg_source_tcp_keepalives_interval {
2574            config.keepalives_interval(keepalives_interval);
2575        }
2576        if let Some(tcp_user_timeout) = params.pg_source_tcp_user_timeout {
2577            config.tcp_user_timeout(tcp_user_timeout);
2578        }
2579
2580        let mut options = vec![];
2581        if let Some(wal_sender_timeout) = params.pg_source_wal_sender_timeout {
2582            options.push(format!(
2583                "--wal_sender_timeout={}",
2584                wal_sender_timeout.as_millis()
2585            ));
2586        };
2587        if params.pg_source_tcp_configure_server {
2588            if let Some(keepalives_retries) = params.pg_source_tcp_keepalives_retries {
2589                options.push(format!("--tcp_keepalives_count={}", keepalives_retries));
2590            }
2591            if let Some(keepalives_idle) = params.pg_source_tcp_keepalives_idle {
2592                options.push(format!(
2593                    "--tcp_keepalives_idle={}",
2594                    keepalives_idle.as_secs()
2595                ));
2596            }
2597            if let Some(keepalives_interval) = params.pg_source_tcp_keepalives_interval {
2598                options.push(format!(
2599                    "--tcp_keepalives_interval={}",
2600                    keepalives_interval.as_secs()
2601                ));
2602            }
2603            if let Some(tcp_user_timeout) = params.pg_source_tcp_user_timeout {
2604                options.push(format!(
2605                    "--tcp_user_timeout={}",
2606                    tcp_user_timeout.as_millis()
2607                ));
2608            }
2609        }
2610        config.options(options.join(" ").as_str());
2611
2612        let tunnel = match &self.tunnel {
2613            Tunnel::Direct => {
2614                // Ensure any host we connect to is resolved to an external address.
2615                let resolved = resolve_address(
2616                    &self.host,
2617                    ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
2618                )
2619                .await?;
2620                mz_postgres_util::TunnelConfig::Direct {
2621                    resolved_ips: Some(resolved),
2622                }
2623            }
2624            Tunnel::Ssh(SshTunnel {
2625                connection_id,
2626                connection,
2627            }) => {
2628                let secret = secrets_reader
2629                    .read_in_task_if(in_task, *connection_id)
2630                    .await?;
2631                let key_pair = SshKeyPair::from_bytes(&secret)?;
2632                // Ensure any ssh-bastion host we connect to is resolved to an external address.
2633                let resolved = resolve_address(
2634                    &connection.host,
2635                    ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
2636                )
2637                .await?;
2638                mz_postgres_util::TunnelConfig::Ssh {
2639                    config: SshTunnelConfig {
2640                        host: resolved
2641                            .iter()
2642                            .map(|a| a.to_string())
2643                            .collect::<BTreeSet<_>>(),
2644                        port: connection.port,
2645                        user: connection.user.clone(),
2646                        key_pair,
2647                    },
2648                }
2649            }
2650            Tunnel::AwsPrivatelink(connection) => {
2651                assert_none!(connection.port);
2652                mz_postgres_util::TunnelConfig::AwsPrivatelink {
2653                    connection_id: connection.connection_id,
2654                }
2655            }
2656            Tunnel::AwsPrivatelinks(_) => {
2657                unreachable!("MATCHING broker rules are only available for Kafka connections.");
2658            }
2659        };
2660
2661        let iam_auth = match self.aws_connection.as_ref() {
2662            None => None,
2663            Some(aws_ref) => Some(
2664                aws_ref
2665                    .connection
2666                    .load_rds_iam_auth(
2667                        &storage_configuration.connection_context,
2668                        aws_ref.connection_id,
2669                        in_task,
2670                        ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
2671                    )
2672                    .await?,
2673            ),
2674        };
2675
2676        Ok(mz_postgres_util::Config::new(
2677            config,
2678            tunnel,
2679            params.ssh_timeout_config,
2680            in_task,
2681            iam_auth,
2682        )?)
2683    }
2684
2685    pub async fn validate(
2686        &self,
2687        _id: CatalogItemId,
2688        storage_configuration: &StorageConfiguration,
2689    ) -> Result<mz_postgres_util::Client, anyhow::Error> {
2690        let config = self
2691            .config(
2692                &storage_configuration.connection_context.secrets_reader,
2693                storage_configuration,
2694                // We are in a normal tokio context during validation, already.
2695                InTask::No,
2696            )
2697            .await?;
2698        let client = config
2699            .connect(
2700                "connection validation",
2701                &storage_configuration.connection_context.ssh_tunnel_manager,
2702            )
2703            .await?;
2704
2705        let wal_level = mz_postgres_util::get_wal_level(&client).await?;
2706
2707        if wal_level < mz_postgres_util::replication::WalLevel::Logical {
2708            Err(PostgresConnectionValidationError::InsufficientWalLevel { wal_level })?;
2709        }
2710
2711        let max_wal_senders = mz_postgres_util::get_max_wal_senders(&client).await?;
2712
2713        if max_wal_senders < 1 {
2714            Err(PostgresConnectionValidationError::ReplicationDisabled)?;
2715        }
2716
2717        let available_replication_slots =
2718            mz_postgres_util::available_replication_slots(&client).await?;
2719
2720        // We need 1 replication slot for the snapshots and 1 for the continuing replication
2721        if available_replication_slots < 2 {
2722            Err(
2723                PostgresConnectionValidationError::InsufficientReplicationSlotsAvailable {
2724                    count: 2,
2725                },
2726            )?;
2727        }
2728
2729        Ok(client)
2730    }
2731}
2732
2733#[derive(Debug, Clone, thiserror::Error)]
2734pub enum PostgresConnectionValidationError {
2735    #[error("PostgreSQL server has insufficient number of replication slots available")]
2736    InsufficientReplicationSlotsAvailable { count: usize },
2737    #[error("server must have wal_level >= logical, but has {wal_level}")]
2738    InsufficientWalLevel {
2739        wal_level: mz_postgres_util::replication::WalLevel,
2740    },
2741    #[error("replication disabled on server")]
2742    ReplicationDisabled,
2743}
2744
2745impl PostgresConnectionValidationError {
2746    pub fn detail(&self) -> Option<String> {
2747        match self {
2748            Self::InsufficientReplicationSlotsAvailable { count } => Some(format!(
2749                "executing this statement requires {} replication slot{}",
2750                count,
2751                if *count == 1 { "" } else { "s" }
2752            )),
2753            _ => None,
2754        }
2755    }
2756
2757    pub fn hint(&self) -> Option<String> {
2758        match self {
2759            Self::InsufficientReplicationSlotsAvailable { .. } => Some(
2760                "you might be able to wait for other sources to finish snapshotting and try again"
2761                    .into(),
2762            ),
2763            Self::ReplicationDisabled => Some("set max_wal_senders to a value > 0".into()),
2764            Self::InsufficientWalLevel { .. } => None,
2765        }
2766    }
2767}
2768
2769impl<C: ConnectionAccess> AlterCompatible for PostgresConnection<C> {
2770    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
2771        let PostgresConnection {
2772            tunnel,
2773            // All non-tunnel options may change arbitrarily
2774            host: _,
2775            port: _,
2776            database: _,
2777            user: _,
2778            password: _,
2779            tls_mode: _,
2780            tls_root_cert: _,
2781            tls_identity: _,
2782            aws_connection: _,
2783        } = self;
2784
2785        let compatibility_checks = [(tunnel.alter_compatible(id, &other.tunnel).is_ok(), "tunnel")];
2786
2787        for (compatible, field) in compatibility_checks {
2788            if !compatible {
2789                tracing::warn!(
2790                    "PostgresConnection incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
2791                    self,
2792                    other
2793                );
2794
2795                return Err(AlterError { id });
2796            }
2797        }
2798        Ok(())
2799    }
2800}
2801
2802/// Specifies how to tunnel a connection.
2803#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2804pub enum Tunnel<C: ConnectionAccess = InlinedConnection> {
2805    /// No tunneling.
2806    Direct,
2807    /// Via the specified SSH tunnel connection.
2808    Ssh(SshTunnel<C>),
2809    /// Via the specified AWS PrivateLink connection.
2810    AwsPrivatelink(AwsPrivatelink),
2811    AwsPrivatelinks(AwsPrivatelinks),
2812}
2813
2814impl<R: ConnectionResolver> IntoInlineConnection<Tunnel, R> for Tunnel<ReferencedConnection> {
2815    fn into_inline_connection(self, r: R) -> Tunnel {
2816        match self {
2817            Tunnel::Direct => Tunnel::Direct,
2818            Tunnel::Ssh(ssh) => Tunnel::Ssh(ssh.into_inline_connection(r)),
2819            Tunnel::AwsPrivatelink(awspl) => Tunnel::AwsPrivatelink(awspl),
2820            Tunnel::AwsPrivatelinks(x) => Tunnel::AwsPrivatelinks(x),
2821        }
2822    }
2823}
2824
2825impl<C: ConnectionAccess> AlterCompatible for Tunnel<C> {
2826    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
2827        let compatible = match (self, other) {
2828            (Self::Ssh(s), Self::Ssh(o)) => s.alter_compatible(id, o).is_ok(),
2829            (s, o) => s == o,
2830        };
2831
2832        if !compatible {
2833            tracing::warn!(
2834                "Tunnel incompatible:\nself:\n{:#?}\n\nother\n{:#?}",
2835                self,
2836                other
2837            );
2838
2839            return Err(AlterError { id });
2840        }
2841
2842        Ok(())
2843    }
2844}
2845
2846/// Specifies which MySQL SSL Mode to use:
2847/// <https://dev.mysql.com/doc/refman/8.0/en/connection-options.html#option_general_ssl-mode>
2848/// This is not available as an enum in the mysql-async crate, so we define our own.
2849#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2850pub enum MySqlSslMode {
2851    Disabled,
2852    Required,
2853    VerifyCa,
2854    VerifyIdentity,
2855}
2856
2857/// A connection to a MySQL server.
2858#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2859pub struct MySqlConnection<C: ConnectionAccess = InlinedConnection> {
2860    /// The hostname of the server.
2861    pub host: String,
2862    /// The port of the server.
2863    pub port: u16,
2864    /// The username to authenticate as.
2865    pub user: StringOrSecret,
2866    /// An optional password for authentication.
2867    pub password: Option<CatalogItemId>,
2868    /// A tunnel through which to route traffic.
2869    pub tunnel: Tunnel<C>,
2870    /// Whether to use TLS for encryption, verify the server's certificate, and identity.
2871    pub tls_mode: MySqlSslMode,
2872    /// An optional root TLS certificate in PEM format, to verify the server's
2873    /// identity.
2874    pub tls_root_cert: Option<StringOrSecret>,
2875    /// An optional TLS client certificate for authentication.
2876    pub tls_identity: Option<TlsIdentity>,
2877    /// Reference to the AWS connection information to be used for IAM authenitcation and
2878    /// assuming AWS roles.
2879    pub aws_connection: Option<AwsConnectionReference<C>>,
2880}
2881
2882impl<R: ConnectionResolver> IntoInlineConnection<MySqlConnection, R>
2883    for MySqlConnection<ReferencedConnection>
2884{
2885    fn into_inline_connection(self, r: R) -> MySqlConnection {
2886        let MySqlConnection {
2887            host,
2888            port,
2889            user,
2890            password,
2891            tunnel,
2892            tls_mode,
2893            tls_root_cert,
2894            tls_identity,
2895            aws_connection,
2896        } = self;
2897
2898        MySqlConnection {
2899            host,
2900            port,
2901            user,
2902            password,
2903            tunnel: tunnel.into_inline_connection(&r),
2904            tls_mode,
2905            tls_root_cert,
2906            tls_identity,
2907            aws_connection: aws_connection.map(|aws| aws.into_inline_connection(&r)),
2908        }
2909    }
2910}
2911
2912impl<C: ConnectionAccess> MySqlConnection<C> {
2913    fn validate_by_default(&self) -> bool {
2914        true
2915    }
2916}
2917
2918impl MySqlConnection<InlinedConnection> {
2919    pub async fn config(
2920        &self,
2921        secrets_reader: &Arc<dyn mz_secrets::SecretsReader>,
2922        storage_configuration: &StorageConfiguration,
2923        in_task: InTask,
2924    ) -> Result<mz_mysql_util::Config, anyhow::Error> {
2925        // TODO(roshan): Set appropriate connection timeouts
2926        let mut opts = mysql_async::OptsBuilder::default()
2927            .ip_or_hostname(&self.host)
2928            .tcp_port(self.port)
2929            .user(Some(&self.user.get_string(in_task, secrets_reader).await?));
2930
2931        if let Some(password) = self.password {
2932            let password = secrets_reader
2933                .read_string_in_task_if(in_task, password)
2934                .await?;
2935            opts = opts.pass(Some(password));
2936        }
2937
2938        // Our `MySqlSslMode` enum matches the official MySQL Client `--ssl-mode` parameter values
2939        // which uses opt-in security features (SSL, CA verification, & Identity verification).
2940        // The mysql_async crate `SslOpts` struct uses an opt-out mechanism for each of these, so
2941        // we need to appropriately disable features to match the intent of each enum value.
2942        let mut ssl_opts = match self.tls_mode {
2943            MySqlSslMode::Disabled => None,
2944            MySqlSslMode::Required => Some(
2945                mysql_async::SslOpts::default()
2946                    .with_danger_accept_invalid_certs(true)
2947                    .with_danger_skip_domain_validation(true),
2948            ),
2949            MySqlSslMode::VerifyCa => {
2950                Some(mysql_async::SslOpts::default().with_danger_skip_domain_validation(true))
2951            }
2952            MySqlSslMode::VerifyIdentity => Some(mysql_async::SslOpts::default()),
2953        };
2954
2955        if matches!(
2956            self.tls_mode,
2957            MySqlSslMode::VerifyCa | MySqlSslMode::VerifyIdentity
2958        ) {
2959            // Trust the platform's roots, not the Mozilla set compiled into
2960            // mysql_async, so a distrusted root goes away with an OS update.
2961            let native = rustls_native_certs::load_native_certs();
2962            for error in &native.errors {
2963                tracing::warn!("failed to load native root certs: {error}");
2964            }
2965            let mut roots: Vec<_> = native
2966                .certs
2967                .into_iter()
2968                .map(|cert| cert.to_vec().into())
2969                .collect();
2970            if let Some(tls_root_cert) = &self.tls_root_cert {
2971                let tls_root_cert = tls_root_cert.get_string(in_task, secrets_reader).await?;
2972                roots.push(tls_root_cert.into_bytes().into());
2973            }
2974            ssl_opts = ssl_opts.map(|opts| {
2975                opts.with_disable_built_in_roots(true)
2976                    .with_root_certs(roots)
2977            });
2978        }
2979
2980        if let Some(identity) = &self.tls_identity {
2981            let key = secrets_reader
2982                .read_string_in_task_if(in_task, identity.key)
2983                .await?;
2984            let cert = identity.cert.get_string(in_task, secrets_reader).await?;
2985            ssl_opts = ssl_opts.map(|opts| {
2986                opts.with_client_identity(Some(mysql_async::ClientIdentity::new(
2987                    cert.into_bytes().into(),
2988                    key.into_bytes().into(),
2989                )))
2990            });
2991        }
2992
2993        opts = opts.ssl_opts(ssl_opts);
2994
2995        let tunnel = match &self.tunnel {
2996            Tunnel::Direct => {
2997                // Ensure any host we connect to is resolved to an external address.
2998                let resolved = resolve_address(
2999                    &self.host,
3000                    ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
3001                )
3002                .await?;
3003                mz_mysql_util::TunnelConfig::Direct {
3004                    resolved_ips: Some(resolved),
3005                }
3006            }
3007            Tunnel::Ssh(SshTunnel {
3008                connection_id,
3009                connection,
3010            }) => {
3011                let secret = secrets_reader
3012                    .read_in_task_if(in_task, *connection_id)
3013                    .await?;
3014                let key_pair = SshKeyPair::from_bytes(&secret)?;
3015                // Ensure any ssh-bastion host we connect to is resolved to an external address.
3016                let resolved = resolve_address(
3017                    &connection.host,
3018                    ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
3019                )
3020                .await?;
3021                mz_mysql_util::TunnelConfig::Ssh {
3022                    config: SshTunnelConfig {
3023                        host: resolved
3024                            .iter()
3025                            .map(|a| a.to_string())
3026                            .collect::<BTreeSet<_>>(),
3027                        port: connection.port,
3028                        user: connection.user.clone(),
3029                        key_pair,
3030                    },
3031                }
3032            }
3033            Tunnel::AwsPrivatelink(connection) => {
3034                assert_none!(connection.port);
3035                mz_mysql_util::TunnelConfig::AwsPrivatelink {
3036                    connection_id: connection.connection_id,
3037                }
3038            }
3039            Tunnel::AwsPrivatelinks(_) => {
3040                unreachable!("MATCHING broker rules are only available for Kafka connections.");
3041            }
3042        };
3043
3044        let iam_auth = match self.aws_connection.as_ref() {
3045            None => None,
3046            Some(aws_ref) => Some(
3047                aws_ref
3048                    .connection
3049                    .load_rds_iam_auth(
3050                        &storage_configuration.connection_context,
3051                        aws_ref.connection_id,
3052                        in_task,
3053                        ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
3054                    )
3055                    .await?,
3056            ),
3057        };
3058
3059        Ok(mz_mysql_util::Config::new(
3060            opts,
3061            tunnel,
3062            storage_configuration.parameters.ssh_timeout_config,
3063            in_task,
3064            storage_configuration
3065                .parameters
3066                .mysql_source_timeouts
3067                .clone(),
3068            iam_auth,
3069        )?)
3070    }
3071
3072    pub async fn validate(
3073        &self,
3074        _id: CatalogItemId,
3075        storage_configuration: &StorageConfiguration,
3076    ) -> Result<MySqlConn, MySqlConnectionValidationError> {
3077        let config = self
3078            .config(
3079                &storage_configuration.connection_context.secrets_reader,
3080                storage_configuration,
3081                // We are in a normal tokio context during validation, already.
3082                InTask::No,
3083            )
3084            .await?;
3085        let mut conn = config
3086            .connect(
3087                "connection validation",
3088                &storage_configuration.connection_context.ssh_tunnel_manager,
3089            )
3090            .await?;
3091
3092        // Check if the MySQL database is configured to allow row-based consistent GTID replication
3093        let mut setting_errors = vec![];
3094        let gtid_res = mz_mysql_util::ensure_gtid_consistency(&mut conn).await;
3095        let binlog_res = mz_mysql_util::ensure_full_row_binlog_format(&mut conn).await;
3096        let order_res = mz_mysql_util::ensure_replication_commit_order(&mut conn).await;
3097        for res in [gtid_res, binlog_res, order_res] {
3098            match res {
3099                Err(MySqlError::InvalidSystemSetting {
3100                    setting,
3101                    expected,
3102                    actual,
3103                }) => {
3104                    setting_errors.push((setting, expected, actual));
3105                }
3106                Err(err) => Err(err)?,
3107                Ok(()) => {}
3108            }
3109        }
3110        if !setting_errors.is_empty() {
3111            Err(MySqlConnectionValidationError::ReplicationSettingsError(
3112                setting_errors,
3113            ))?;
3114        }
3115
3116        Ok(conn)
3117    }
3118}
3119
3120#[derive(Debug, thiserror::Error)]
3121pub enum MySqlConnectionValidationError {
3122    #[error("Invalid MySQL system replication settings")]
3123    ReplicationSettingsError(Vec<(String, String, String)>),
3124    #[error(transparent)]
3125    Client(#[from] MySqlError),
3126    #[error("{}", .0.display_with_causes())]
3127    Other(#[from] anyhow::Error),
3128}
3129
3130impl MySqlConnectionValidationError {
3131    pub fn detail(&self) -> Option<String> {
3132        match self {
3133            Self::ReplicationSettingsError(settings) => Some(format!(
3134                "Invalid MySQL system replication settings: {}",
3135                itertools::join(
3136                    settings.iter().map(|(setting, expected, actual)| format!(
3137                        "{}: expected {}, got {}",
3138                        setting, expected, actual
3139                    )),
3140                    "; "
3141                )
3142            )),
3143            _ => None,
3144        }
3145    }
3146
3147    pub fn hint(&self) -> Option<String> {
3148        match self {
3149            Self::ReplicationSettingsError(_) => {
3150                Some("Set the necessary MySQL database system settings.".into())
3151            }
3152            _ => None,
3153        }
3154    }
3155}
3156
3157impl<C: ConnectionAccess> AlterCompatible for MySqlConnection<C> {
3158    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
3159        let MySqlConnection {
3160            tunnel,
3161            // All non-tunnel options may change arbitrarily
3162            host: _,
3163            port: _,
3164            user: _,
3165            password: _,
3166            tls_mode: _,
3167            tls_root_cert: _,
3168            tls_identity: _,
3169            aws_connection: _,
3170        } = self;
3171
3172        let compatibility_checks = [(tunnel.alter_compatible(id, &other.tunnel).is_ok(), "tunnel")];
3173
3174        for (compatible, field) in compatibility_checks {
3175            if !compatible {
3176                tracing::warn!(
3177                    "MySqlConnection incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
3178                    self,
3179                    other
3180                );
3181
3182                return Err(AlterError { id });
3183            }
3184        }
3185        Ok(())
3186    }
3187}
3188
3189/// Details how to connect to an instance of Microsoft SQL Server.
3190///
3191/// For specifics of connecting to SQL Server for purposes of creating a
3192/// Materialize Source, see [`SqlServerSourceConnection`] which wraps this type.
3193///
3194/// [`SqlServerSourceConnection`]: crate::sources::SqlServerSourceConnection
3195#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3196pub struct SqlServerConnectionDetails<C: ConnectionAccess = InlinedConnection> {
3197    /// The hostname of the server.
3198    pub host: String,
3199    /// The port of the server.
3200    pub port: u16,
3201    /// Database we should connect to.
3202    pub database: String,
3203    /// The username to authenticate as.
3204    pub user: StringOrSecret,
3205    /// Password used for authentication.
3206    pub password: CatalogItemId,
3207    /// A tunnel through which to route traffic.
3208    pub tunnel: Tunnel<C>,
3209    /// Level of encryption to use for the connection.
3210    pub encryption: mz_sql_server_util::config::EncryptionLevel,
3211    /// Certificate validation policy
3212    pub certificate_validation_policy: mz_sql_server_util::config::CertificateValidationPolicy,
3213    /// TLS CA Certifiecate in PEM format
3214    pub tls_root_cert: Option<StringOrSecret>,
3215}
3216
3217impl<C: ConnectionAccess> SqlServerConnectionDetails<C> {
3218    fn validate_by_default(&self) -> bool {
3219        true
3220    }
3221}
3222
3223impl SqlServerConnectionDetails<InlinedConnection> {
3224    /// Attempts to open a connection to the upstream SQL Server instance.
3225    pub async fn validate(
3226        &self,
3227        _id: CatalogItemId,
3228        storage_configuration: &StorageConfiguration,
3229    ) -> Result<mz_sql_server_util::Client, anyhow::Error> {
3230        let config = self
3231            .resolve_config(
3232                &storage_configuration.connection_context.secrets_reader,
3233                storage_configuration,
3234                InTask::No,
3235            )
3236            .await?;
3237        tracing::debug!(?config, "Validating SQL Server connection");
3238
3239        let mut client = mz_sql_server_util::Client::connect(config).await?;
3240
3241        // Ensure the upstream SQL Server instance is configured to allow CDC.
3242        //
3243        // Run all of the checks necessary and collect the errors to provide the best
3244        // guidance as to which system settings need to be enabled.
3245        let mut replication_errors = vec![];
3246        for error in [
3247            mz_sql_server_util::inspect::ensure_database_cdc_enabled(&mut client).await,
3248            mz_sql_server_util::inspect::ensure_snapshot_isolation_enabled(&mut client).await,
3249            mz_sql_server_util::inspect::ensure_sql_server_agent_running(&mut client).await,
3250        ] {
3251            match error {
3252                Err(mz_sql_server_util::SqlServerError::InvalidSystemSetting {
3253                    name,
3254                    expected,
3255                    actual,
3256                }) => replication_errors.push((name, expected, actual)),
3257                Err(other) => Err(other)?,
3258                Ok(()) => (),
3259            }
3260        }
3261        if !replication_errors.is_empty() {
3262            Err(SqlServerConnectionValidationError::ReplicationSettingsError(replication_errors))?;
3263        }
3264
3265        Ok(client)
3266    }
3267
3268    /// Resolve all of the connection details (e.g. read from the [`SecretsReader`])
3269    /// so the returned [`Config`] can be used to open a connection with the
3270    /// upstream system.
3271    ///
3272    /// The provided [`InTask`] argument determines whether any I/O is run in an
3273    /// [`mz_ore::task`] (i.e. a different thread) or directly in the returned
3274    /// future. The main goal here is to prevent running I/O in timely threads.
3275    ///
3276    /// [`Config`]: mz_sql_server_util::Config
3277    pub async fn resolve_config(
3278        &self,
3279        secrets_reader: &Arc<dyn mz_secrets::SecretsReader>,
3280        storage_configuration: &StorageConfiguration,
3281        in_task: InTask,
3282    ) -> Result<mz_sql_server_util::Config, anyhow::Error> {
3283        let dyncfg = storage_configuration.config_set();
3284        let mut inner_config = tiberius::Config::new();
3285
3286        // Setup default connection params.
3287        inner_config.host(&self.host);
3288        inner_config.port(self.port);
3289        inner_config.database(self.database.clone());
3290        inner_config.encryption(self.encryption.into());
3291        match self.certificate_validation_policy {
3292            mz_sql_server_util::config::CertificateValidationPolicy::TrustAll => {
3293                inner_config.trust_cert()
3294            }
3295            mz_sql_server_util::config::CertificateValidationPolicy::VerifyCA => {
3296                inner_config.trust_cert_ca_pem(
3297                    self.tls_root_cert
3298                        .as_ref()
3299                        .unwrap()
3300                        .get_string(in_task, secrets_reader)
3301                        .await
3302                        .context("ca certificate")?,
3303                );
3304            }
3305            mz_sql_server_util::config::CertificateValidationPolicy::VerifySystem => (), // no-op
3306        }
3307
3308        inner_config.application_name("materialize");
3309
3310        // Read our auth settings from
3311        let user = self
3312            .user
3313            .get_string(in_task, secrets_reader)
3314            .await
3315            .context("username")?;
3316        let password = secrets_reader
3317            .read_string_in_task_if(in_task, self.password)
3318            .await
3319            .context("password")?;
3320        // TODO(sql_server3): Support other methods of authentication besides
3321        // username and password.
3322        inner_config.authentication(tiberius::AuthMethod::sql_server(user, password));
3323
3324        // Prevent users from probing our internal network ports by trying to
3325        // connect to localhost, or another non-external IP.
3326        let enforce_external_addresses = ENFORCE_EXTERNAL_ADDRESSES.get(dyncfg);
3327
3328        let tunnel = match &self.tunnel {
3329            Tunnel::Direct => {
3330                let resolved_addresses: Vec<SocketAddr> =
3331                    resolve_address(&self.host, enforce_external_addresses)
3332                        .await?
3333                        .into_iter()
3334                        .map(|ip| SocketAddr::new(ip, self.port))
3335                        .collect();
3336                mz_sql_server_util::config::TunnelConfig::Direct {
3337                    resolved_addresses: resolved_addresses.into_boxed_slice(),
3338                }
3339            }
3340            Tunnel::Ssh(SshTunnel {
3341                connection_id,
3342                connection: ssh_connection,
3343            }) => {
3344                let secret = secrets_reader
3345                    .read_in_task_if(in_task, *connection_id)
3346                    .await
3347                    .context("ssh secret")?;
3348                let key_pair = SshKeyPair::from_bytes(&secret).context("ssh key pair")?;
3349                // Ensure any SSH-bastion host we connect to is resolved to an
3350                // external address.
3351                let addresses = resolve_address(&ssh_connection.host, enforce_external_addresses)
3352                    .await
3353                    .context("ssh tunnel")?;
3354
3355                let config = SshTunnelConfig {
3356                    host: addresses.into_iter().map(|a| a.to_string()).collect(),
3357                    port: ssh_connection.port,
3358                    user: ssh_connection.user.clone(),
3359                    key_pair,
3360                };
3361                mz_sql_server_util::config::TunnelConfig::Ssh {
3362                    config,
3363                    manager: storage_configuration
3364                        .connection_context
3365                        .ssh_tunnel_manager
3366                        .clone(),
3367                    timeout: storage_configuration.parameters.ssh_timeout_config.clone(),
3368                    host: self.host.clone(),
3369                    port: self.port,
3370                }
3371            }
3372            Tunnel::AwsPrivatelink(private_link_connection) => {
3373                assert_none!(private_link_connection.port);
3374                mz_sql_server_util::config::TunnelConfig::AwsPrivatelink {
3375                    connection_id: private_link_connection.connection_id,
3376                    port: self.port,
3377                }
3378            }
3379            Tunnel::AwsPrivatelinks(_) => {
3380                unreachable!("MATCHING broker rules are only available for Kafka connections.");
3381            }
3382        };
3383
3384        Ok(mz_sql_server_util::Config::new(
3385            inner_config,
3386            tunnel,
3387            in_task,
3388        ))
3389    }
3390}
3391
3392#[derive(Debug, Clone, thiserror::Error)]
3393pub enum SqlServerConnectionValidationError {
3394    #[error("Invalid SQL Server system replication settings")]
3395    ReplicationSettingsError(Vec<(String, String, String)>),
3396}
3397
3398impl SqlServerConnectionValidationError {
3399    pub fn detail(&self) -> Option<String> {
3400        match self {
3401            Self::ReplicationSettingsError(settings) => Some(format!(
3402                "Invalid SQL Server system replication settings: {}",
3403                itertools::join(
3404                    settings.iter().map(|(setting, expected, actual)| format!(
3405                        "{}: expected {}, got {}",
3406                        setting, expected, actual
3407                    )),
3408                    "; "
3409                )
3410            )),
3411        }
3412    }
3413
3414    pub fn hint(&self) -> Option<String> {
3415        match self {
3416            _ => None,
3417        }
3418    }
3419}
3420
3421impl<R: ConnectionResolver> IntoInlineConnection<SqlServerConnectionDetails, R>
3422    for SqlServerConnectionDetails<ReferencedConnection>
3423{
3424    fn into_inline_connection(self, r: R) -> SqlServerConnectionDetails {
3425        let SqlServerConnectionDetails {
3426            host,
3427            port,
3428            database,
3429            user,
3430            password,
3431            tunnel,
3432            encryption,
3433            certificate_validation_policy,
3434            tls_root_cert,
3435        } = self;
3436
3437        SqlServerConnectionDetails {
3438            host,
3439            port,
3440            database,
3441            user,
3442            password,
3443            tunnel: tunnel.into_inline_connection(&r),
3444            encryption,
3445            certificate_validation_policy,
3446            tls_root_cert,
3447        }
3448    }
3449}
3450
3451impl<C: ConnectionAccess> AlterCompatible for SqlServerConnectionDetails<C> {
3452    fn alter_compatible(
3453        &self,
3454        id: mz_repr::GlobalId,
3455        other: &Self,
3456    ) -> Result<(), crate::controller::AlterError> {
3457        let SqlServerConnectionDetails {
3458            tunnel,
3459            // TODO(sql_server2): Figure out how these variables are allowed to change.
3460            host: _,
3461            port: _,
3462            database: _,
3463            user: _,
3464            password: _,
3465            encryption: _,
3466            certificate_validation_policy: _,
3467            tls_root_cert: _,
3468        } = self;
3469
3470        let compatibility_checks = [(tunnel.alter_compatible(id, &other.tunnel).is_ok(), "tunnel")];
3471
3472        for (compatible, field) in compatibility_checks {
3473            if !compatible {
3474                tracing::warn!(
3475                    "SqlServerConnectionDetails incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
3476                    self,
3477                    other
3478                );
3479
3480                return Err(AlterError { id });
3481            }
3482        }
3483        Ok(())
3484    }
3485}
3486
3487/// A connection to an SSH tunnel.
3488#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3489pub struct SshConnection {
3490    pub host: String,
3491    pub port: u16,
3492    pub user: String,
3493}
3494
3495use self::inline::{
3496    ConnectionAccess, ConnectionResolver, InlinedConnection, IntoInlineConnection,
3497    ReferencedConnection,
3498};
3499
3500impl AlterCompatible for SshConnection {
3501    fn alter_compatible(&self, _id: GlobalId, _other: &Self) -> Result<(), AlterError> {
3502        // Every element of the SSH connection is configurable.
3503        Ok(())
3504    }
3505}
3506
3507/// Specifies an AWS PrivateLink service for a [`Tunnel`].
3508#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3509pub struct AwsPrivatelink {
3510    /// The ID of the connection to the AWS PrivateLink service.
3511    pub connection_id: CatalogItemId,
3512    // The availability zone to use when connecting to the AWS PrivateLink service.
3513    pub availability_zone: Option<String>,
3514    /// The port to use when connecting to the AWS PrivateLink service, if
3515    /// different from the port in [`KafkaBroker::address`].
3516    pub port: Option<u16>,
3517}
3518
3519impl AlterCompatible for AwsPrivatelink {
3520    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
3521        let AwsPrivatelink {
3522            connection_id,
3523            availability_zone: _,
3524            port: _,
3525        } = self;
3526
3527        let compatibility_checks = [(connection_id == &other.connection_id, "connection_id")];
3528
3529        for (compatible, field) in compatibility_checks {
3530            if !compatible {
3531                tracing::warn!(
3532                    "AwsPrivatelink incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
3533                    self,
3534                    other
3535                );
3536
3537                return Err(AlterError { id });
3538            }
3539        }
3540
3541        Ok(())
3542    }
3543}
3544
3545#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3546pub struct AwsPrivatelinks {
3547    /// Route to brokers through PrivateLink connections according to these rules.
3548    /// Exact-match rules (no wildcards) are used as bootstrap brokers.
3549    /// Wildcard rules are applied dynamically to discovered brokers.
3550    pub rules: Vec<AwsPrivatelinkRule>,
3551}
3552
3553#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3554pub struct AwsPrivatelinkRule {
3555    /// Given a broker's host:port, should we use this route?
3556    pub pattern: ConnectionRulePattern,
3557    /// Route to the broker through this PrivateLink connection.
3558    pub to: AwsPrivatelink,
3559}
3560
3561/// Specifies an SSH tunnel connection.
3562#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3563pub struct SshTunnel<C: ConnectionAccess = InlinedConnection> {
3564    /// id of the ssh connection
3565    pub connection_id: CatalogItemId,
3566    /// ssh connection object
3567    pub connection: C::Ssh,
3568}
3569
3570impl<R: ConnectionResolver> IntoInlineConnection<SshTunnel, R> for SshTunnel<ReferencedConnection> {
3571    fn into_inline_connection(self, r: R) -> SshTunnel {
3572        let SshTunnel {
3573            connection,
3574            connection_id,
3575        } = self;
3576
3577        SshTunnel {
3578            connection: r.resolve_connection(connection).unwrap_ssh(),
3579            connection_id,
3580        }
3581    }
3582}
3583
3584impl SshTunnel<InlinedConnection> {
3585    /// Like [`SshTunnelConfig::connect`], but the SSH key is loaded from a
3586    /// secret.
3587    async fn connect(
3588        &self,
3589        storage_configuration: &StorageConfiguration,
3590        remote_host: &str,
3591        remote_port: u16,
3592        in_task: InTask,
3593    ) -> Result<ManagedSshTunnelHandle, anyhow::Error> {
3594        // Ensure any ssh-bastion host we connect to is resolved to an external address.
3595        let resolved = resolve_address(
3596            &self.connection.host,
3597            ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
3598        )
3599        .await?;
3600        storage_configuration
3601            .connection_context
3602            .ssh_tunnel_manager
3603            .connect(
3604                SshTunnelConfig {
3605                    host: resolved
3606                        .iter()
3607                        .map(|a| a.to_string())
3608                        .collect::<BTreeSet<_>>(),
3609                    port: self.connection.port,
3610                    user: self.connection.user.clone(),
3611                    key_pair: SshKeyPair::from_bytes(
3612                        &storage_configuration
3613                            .connection_context
3614                            .secrets_reader
3615                            .read_in_task_if(in_task, self.connection_id)
3616                            .await?,
3617                    )?,
3618                },
3619                remote_host,
3620                remote_port,
3621                storage_configuration.parameters.ssh_timeout_config,
3622                in_task,
3623            )
3624            .await
3625    }
3626}
3627
3628impl<C: ConnectionAccess> AlterCompatible for SshTunnel<C> {
3629    fn alter_compatible(&self, id: GlobalId, other: &Self) -> Result<(), AlterError> {
3630        let SshTunnel {
3631            connection_id,
3632            connection,
3633        } = self;
3634
3635        let compatibility_checks = [
3636            (connection_id == &other.connection_id, "connection_id"),
3637            (
3638                connection.alter_compatible(id, &other.connection).is_ok(),
3639                "connection",
3640            ),
3641        ];
3642
3643        for (compatible, field) in compatibility_checks {
3644            if !compatible {
3645                tracing::warn!(
3646                    "SshTunnel incompatible at {field}:\nself:\n{:#?}\n\nother\n{:#?}",
3647                    self,
3648                    other
3649                );
3650
3651                return Err(AlterError { id });
3652            }
3653        }
3654
3655        Ok(())
3656    }
3657}
3658
3659impl SshConnection {
3660    #[allow(clippy::unused_async)]
3661    async fn validate(
3662        &self,
3663        id: CatalogItemId,
3664        storage_configuration: &StorageConfiguration,
3665    ) -> Result<(), anyhow::Error> {
3666        let secret = storage_configuration
3667            .connection_context
3668            .secrets_reader
3669            .read_in_task_if(
3670                // We are in a normal tokio context during validation, already.
3671                InTask::No,
3672                id,
3673            )
3674            .await?;
3675        let key_pair = SshKeyPair::from_bytes(&secret)?;
3676
3677        // Ensure any ssh-bastion host we connect to is resolved to an external address.
3678        let resolved = resolve_address(
3679            &self.host,
3680            ENFORCE_EXTERNAL_ADDRESSES.get(storage_configuration.config_set()),
3681        )
3682        .await?;
3683
3684        let config = SshTunnelConfig {
3685            host: resolved
3686                .iter()
3687                .map(|a| a.to_string())
3688                .collect::<BTreeSet<_>>(),
3689            port: self.port,
3690            user: self.user.clone(),
3691            key_pair,
3692        };
3693        // Note that we do NOT use the `SshTunnelManager` here, as we want to validate that we
3694        // can actually create a new connection to the ssh bastion, without tunneling.
3695        config
3696            .validate(storage_configuration.parameters.ssh_timeout_config)
3697            .await
3698    }
3699
3700    fn validate_by_default(&self) -> bool {
3701        false
3702    }
3703}
3704
3705impl AwsPrivatelinkConnection {
3706    #[allow(clippy::unused_async)]
3707    async fn validate(
3708        &self,
3709        id: CatalogItemId,
3710        storage_configuration: &StorageConfiguration,
3711    ) -> Result<(), ConnectionValidationError> {
3712        // An endpoint for an unusable service name reports a misleading
3713        // condition (missing availability zones), so check the name first.
3714        Self::check_service_name(&self.service_name)?;
3715
3716        let Some(ref cloud_resource_reader) = storage_configuration
3717            .connection_context
3718            .cloud_resource_reader
3719        else {
3720            return Err(anyhow!("AWS PrivateLink connections are unsupported").into());
3721        };
3722
3723        // No need to optionally run this in a task, as we are just validating from envd.
3724        let status = cloud_resource_reader.read(id).await?;
3725
3726        let availability = status
3727            .conditions
3728            .as_ref()
3729            .and_then(|conditions| conditions.iter().find(|c| c.type_ == "Available"));
3730
3731        match availability {
3732            Some(condition) if condition.status == "True" => Ok(()),
3733            Some(condition) => Err(anyhow!("{}", condition.message).into()),
3734            None => Err(anyhow!("Endpoint availability is unknown").into()),
3735        }
3736    }
3737
3738    fn validate_by_default(&self) -> bool {
3739        false
3740    }
3741}
3742
3743#[cfg(test)]
3744mod tests {
3745    use super::*;
3746
3747    #[mz_ore::test]
3748    fn test_catalog_headers() {
3749        let props = BTreeMap::from_iter(
3750            [
3751                (REST_CATALOG_PROP_URI, "https://catalog.example"),
3752                (REST_CATALOG_PROP_WAREHOUSE, "wh"),
3753                ("header.x-goog-user-project", "some-project"),
3754                (REST_CATALOG_PROP_ACCESS_DELEGATION, "vended-credentials"),
3755            ]
3756            .map(|(k, v)| (k.to_string(), v.to_string())),
3757        );
3758
3759        // Only `header.*` props become headers, and the prefix is stripped. Header names are
3760        // matched case-insensitively, so the delegation prop's mixed-case spelling still lands.
3761        let headers = IcebergCatalogConnection::catalog_headers(&props).expect("valid headers");
3762        assert_eq!(headers.len(), 2);
3763        assert_eq!(headers["x-goog-user-project"], "some-project");
3764        assert_eq!(headers["x-iceberg-access-delegation"], "vended-credentials");
3765
3766        // A prop whose name is not a legal header is an error rather than a dropped header: it
3767        // would otherwise mean silently talking to the catalog differently than asked.
3768        let props = BTreeMap::from([("header.bad name".to_string(), "v".to_string())]);
3769        assert!(IcebergCatalogConnection::catalog_headers(&props).is_err());
3770    }
3771
3772    #[mz_ore::test]
3773    fn test_check_service_name() {
3774        // Customer-owned and AWS-managed endpoint services are both accepted,
3775        // as is anything else that could be an endpoint service name.
3776        for name in [
3777            "com.amazonaws.vpce.us-east-1.vpce-svc-0e123abc123198abc",
3778            "com.amazonaws.vpce.test.vpce-svc-e2e-test",
3779            "com.amazonaws.us-east-1.s3",
3780            "com.amazonaws.anything",
3781        ] {
3782            assert_eq!(
3783                AwsPrivatelinkConnection::check_service_name(name),
3784                Ok(()),
3785                "expected {name} to be accepted"
3786            );
3787        }
3788
3789        for name in [
3790            "",
3791            "com.amazonaws",
3792            "vpce-svc-0e123abc123198abc",
3793            "my-db-lb-0123456789abcdef.elb.eu-central-1.amazonaws.com",
3794            "db.internal.example.org",
3795        ] {
3796            let err = AwsPrivatelinkConnection::check_service_name(name)
3797                .expect_err("service name should be rejected");
3798            assert_eq!(err.name, name);
3799        }
3800    }
3801}