1use 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;
24use 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
100const OAUTH2_PARAM_SCOPE: &str = "scope";
106
107const REST_CATALOG_PROP_OAUTH2_SERVER_URI: &str = "oauth2-server-uri";
108const REST_CATALOG_HEADER_PROP_PREFIX: &str = "header.";
111const REST_CATALOG_PROP_ACCESS_DELEGATION: &str = "header.X-Iceberg-Access-Delegation";
114
115#[derive(Debug)]
123struct AwsSdkCredentialLoader {
124 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 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
168fn 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
188struct Sigv4Authenticator {
194 provider: SharedCredentialsProvider,
195 region: String,
196 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, ¶ms).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 async fn invalidate_cache(&self) -> iceberg::Result<()> {
284 Ok(())
285 }
286 async fn regenerate_cache(&self) -> iceberg::Result<()> {
287 Ok(())
288 }
289}
290
291#[async_trait::async_trait]
293trait SecretsReaderExt {
294 async fn read_in_task_if(
296 &self,
297 in_task: InTask,
298 id: CatalogItemId,
299 ) -> Result<Vec<u8>, anyhow::Error>;
300
301 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#[derive(Debug, Clone)]
338pub struct ConnectionContext {
339 pub environment_id: String,
346 pub librdkafka_log_level: tracing::Level,
348 pub aws_external_id_prefix: Option<AwsExternalIdPrefix>,
350 pub aws_connection_role_arn: Option<String>,
353 pub secrets_reader: Arc<dyn SecretsReader>,
355 pub cloud_resource_reader: Option<Arc<dyn CloudResourceReader>>,
357 pub ssh_tunnel_manager: SshTunnelManager,
359 pub aws_credentials_cache: AwsCredentialsCache,
362}
363
364impl ConnectionContext {
365 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 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 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 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#[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 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 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#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
656pub enum IcebergCatalogAuth<C: ConnectionAccess = InlinedConnection> {
657 OAuth {
659 credential: StringOrSecret,
661 scope: Option<String>,
663 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 pub warehouse: Option<String>,
679 pub access_delegation: Option<IcebergAccessDelegation>,
686 pub storage_provider: IcebergStorageProvider,
691}
692
693#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
696pub enum IcebergAccessDelegation {
697 VendedCredentials,
699}
700
701impl IcebergAccessDelegation {
702 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 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 pub aws_connection: AwsConnectionReference<C>,
732 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#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
812pub enum IcebergStorageProvider {
813 S3,
814 Gcs,
815 Adls,
816}
817
818impl IcebergStorageProvider {
819 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 pub catalog: IcebergCatalogImpl<C>,
875 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 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 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 let credentials_provider = match &aws_auth {
1017 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 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 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 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 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 let client = reqwest_0_12::Client::new();
1195
1196 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 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 let token_endpoint = match server_url {
1247 Some(server_url) => server_url.clone(),
1248 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 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 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 match rest.storage_provider {
1285 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 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 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 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 Self::gcs_storage_factory(endpoint, &client, &token, &headers),
1364 Some(iceberg_catalog_rest::BearerTokenAuthenticator::new(token)),
1365 )
1366 }
1367 };
1368
1369 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 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 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 Ok(())
1424 }
1425}
1426
1427#[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 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 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#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
1501pub struct KafkaBroker<C: ConnectionAccess = InlinedConnection> {
1502 pub address: String,
1504 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 pub replication_factor: Option<NonNeg<i32>>,
1525 pub partition_count: Option<NonNeg<i32>>,
1528 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 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 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 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 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 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 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 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 format!(
1705 "{}:{}",
1706 vpc_endpoint_host(
1707 t.connection_id,
1708 None, ),
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 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 }
1843 Tunnel::AwsPrivatelink(pl) => {
1844 context.set_default_tunnel(TunnelConfig::StaticHost(
1845 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 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 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 }
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 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 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 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 Err(err) => {
2012 let main_err = error_rx.try_iter().reduce(|cur, new| match cur {
2016 MzKafkaError::Internal(_) => new,
2017 _ => cur,
2018 });
2019
2020 drop(consumer);
2024
2025 match main_err {
2026 Some(err) => Err(err.into()),
2027 None => Err(err.into()),
2028 }
2029 }
2030 }
2031 }
2032
2033 fn from_default_aws_privatelink(pl: &AwsPrivatelink) -> BrokerRewrite {
2035 BrokerRewrite {
2036 host: vpc_endpoint_host(
2037 pl.connection_id,
2038 None, ),
2040 port: pl.port,
2041 }
2042 }
2043
2044 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#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2114pub struct CsrConnection<C: ConnectionAccess = InlinedConnection> {
2115 pub url: Url,
2117 pub tls_root_cert: Option<StringOrSecret>,
2119 pub tls_identity: Option<TlsIdentity>,
2122 pub http_auth: Option<CsrConnectionHttpAuth>,
2124 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 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 let host = self
2214 .url
2215 .host_str()
2216 .ok_or_else(|| anyhow!("url missing host"))?;
2217 match &self.tunnel {
2218 Tunnel::Direct => {
2219 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 self.url.port_or_known_default().unwrap_or(80),
2241 in_task,
2242 )
2243 .await
2244 .map_err(CsrConnectError::Ssh)?;
2245
2246 client_config = client_config
2252 .resolve_to_addrs(host, &[SocketAddr::new(ssh_tunnel.local_addr().ip(), 0)])
2259 .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 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 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#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2350pub struct GlueSchemaRegistryConnection<C: ConnectionAccess = InlinedConnection> {
2351 pub aws_connection: AwsConnectionReference<C>,
2354 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 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 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 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#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2444pub struct TlsIdentity {
2445 pub cert: StringOrSecret,
2447 pub key: CatalogItemId,
2450}
2451
2452#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2454pub struct CsrConnectionHttpAuth {
2455 pub username: StringOrSecret,
2457 pub password: Option<CatalogItemId>,
2459}
2460
2461#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2463pub struct PostgresConnection<C: ConnectionAccess = InlinedConnection> {
2464 pub host: String,
2466 pub port: u16,
2468 pub database: String,
2470 pub user: StringOrSecret,
2472 pub password: Option<CatalogItemId>,
2474 pub tunnel: Tunnel<C>,
2476 pub tls_mode: SslMode,
2478 pub tls_root_cert: Option<StringOrSecret>,
2481 pub tls_identity: Option<TlsIdentity>,
2483 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 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 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 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 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 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#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2804pub enum Tunnel<C: ConnectionAccess = InlinedConnection> {
2805 Direct,
2807 Ssh(SshTunnel<C>),
2809 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#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2850pub enum MySqlSslMode {
2851 Disabled,
2852 Required,
2853 VerifyCa,
2854 VerifyIdentity,
2855}
2856
2857#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
2859pub struct MySqlConnection<C: ConnectionAccess = InlinedConnection> {
2860 pub host: String,
2862 pub port: u16,
2864 pub user: StringOrSecret,
2866 pub password: Option<CatalogItemId>,
2868 pub tunnel: Tunnel<C>,
2870 pub tls_mode: MySqlSslMode,
2872 pub tls_root_cert: Option<StringOrSecret>,
2875 pub tls_identity: Option<TlsIdentity>,
2877 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 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 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 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 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 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 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 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 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#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3196pub struct SqlServerConnectionDetails<C: ConnectionAccess = InlinedConnection> {
3197 pub host: String,
3199 pub port: u16,
3201 pub database: String,
3203 pub user: StringOrSecret,
3205 pub password: CatalogItemId,
3207 pub tunnel: Tunnel<C>,
3209 pub encryption: mz_sql_server_util::config::EncryptionLevel,
3211 pub certificate_validation_policy: mz_sql_server_util::config::CertificateValidationPolicy,
3213 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 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 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 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 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 => (), }
3307
3308 inner_config.application_name("materialize");
3309
3310 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 inner_config.authentication(tiberius::AuthMethod::sql_server(user, password));
3323
3324 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 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 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#[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 Ok(())
3504 }
3505}
3506
3507#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3509pub struct AwsPrivatelink {
3510 pub connection_id: CatalogItemId,
3512 pub availability_zone: Option<String>,
3514 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 pub rules: Vec<AwsPrivatelinkRule>,
3551}
3552
3553#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3554pub struct AwsPrivatelinkRule {
3555 pub pattern: ConnectionRulePattern,
3557 pub to: AwsPrivatelink,
3559}
3560
3561#[derive(Clone, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
3563pub struct SshTunnel<C: ConnectionAccess = InlinedConnection> {
3564 pub connection_id: CatalogItemId,
3566 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 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 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 InTask::No,
3672 id,
3673 )
3674 .await?;
3675 let key_pair = SshKeyPair::from_bytes(&secret)?;
3676
3677 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 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 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 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 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 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 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}