1use std::collections::{BTreeMap, BTreeSet};
13
14use anyhow::Context;
15use array_concat::concat_arrays;
16use itertools::Itertools;
17use maplit::btreemap;
18use mz_ore::num::NonNeg;
19use mz_ore::str::StrExt;
20use mz_repr::CatalogItemId;
21use mz_sql_parser::ast::ConnectionOptionName::*;
22use mz_sql_parser::ast::display::AstDisplay;
23use mz_sql_parser::ast::{
24 ConnectionDefaultAwsPrivatelink, ConnectionOption, ConnectionOptionName, CreateConnectionType,
25 KafkaBroker, KafkaBrokerAwsPrivatelinkOption, KafkaBrokerAwsPrivatelinkOptionName,
26 KafkaBrokerTunnel, KafkaMatchingBrokerRule,
27};
28use mz_ssh_util::keys::SshKeyPair;
29use mz_storage_types::connections::aws::{
30 AwsAssumeRole, AwsAuth, AwsConnection, AwsConnectionReference, AwsCredentials,
31};
32use mz_storage_types::connections::gcp::{GcpConnection, GcpConnectionReference};
33use mz_storage_types::connections::inline::ReferencedConnection;
34use mz_storage_types::connections::string_or_secret::StringOrSecret;
35use mz_storage_types::connections::{
36 AwsPrivatelink, AwsPrivatelinkConnection, AwsPrivatelinkRule, CsrConnection,
37 CsrConnectionHttpAuth, GlueSchemaRegistryConnection, IcebergAccessDelegation,
38 IcebergCatalogAuth, IcebergCatalogConnection, IcebergCatalogImpl, IcebergCatalogType,
39 IcebergStorageProvider, KafkaConnection, KafkaSaslConfig, KafkaTlsConfig, KafkaTopicOptions,
40 MySqlConnection, MySqlSslMode, PostgresConnection, RestIcebergCatalog,
41 S3TablesRestIcebergCatalog, SqlServerConnectionDetails, SshConnection, SshTunnel, TlsIdentity,
42 Tunnel,
43};
44
45use crate::names::Aug;
46use crate::plan::statement::{Connection, ResolvedItemName};
47use crate::plan::with_options::{self};
48use crate::plan::{ConnectionDetails, PlanError, SshKey, StatementContext};
49use crate::session::vars;
50
51generate_extracted_config!(
52 ConnectionOption,
53 (AccessDelegation, IcebergAccessDelegation),
54 (StorageProvider, IcebergStorageProvider),
55 (AccessKeyId, StringOrSecret),
56 (AssumeRoleArn, String),
57 (AssumeRoleSessionName, String),
58 (AvailabilityZones, Vec<String>),
59 (AwsConnection, with_options::Object),
60 (AwsPrivatelink, ConnectionDefaultAwsPrivatelink<Aug>),
61 (Broker, Vec<KafkaBroker<Aug>>),
62 (Brokers, with_options::BrokersList),
63 (Credential, StringOrSecret),
64 (Database, String),
65 (Endpoint, String),
66 (GcpConnection, with_options::Object),
67 (Host, String),
68 (Oauth2ServerUrl, String),
69 (Password, with_options::Secret),
70 (Port, u16),
71 (ProgressTopic, String),
72 (ProgressTopicReplicationFactor, i32),
73 (PublicKey1, String),
74 (PublicKey2, String),
75 (Region, String),
76 (Registry, String),
77 (SaslMechanisms, String),
78 (SaslPassword, with_options::Secret),
79 (SaslUsername, StringOrSecret),
80 (Scope, String),
81 (SecretAccessKey, with_options::Secret),
82 (SecurityProtocol, String),
83 (ServiceAccountKey, with_options::Secret),
84 (ServiceName, String),
85 (SshTunnel, with_options::Object),
86 (SslCertificate, StringOrSecret),
87 (SslCertificateAuthority, StringOrSecret),
88 (SslKey, with_options::Secret),
89 (SslMode, String),
90 (SessionToken, StringOrSecret),
91 (CatalogType, IcebergCatalogType),
92 (Url, String),
93 (User, StringOrSecret),
94 (Warehouse, String)
95);
96
97generate_extracted_config!(
98 KafkaBrokerAwsPrivatelinkOption,
99 (AvailabilityZone, String),
100 (Port, u16)
101);
102
103pub(crate) const INALTERABLE_OPTIONS: &[ConnectionOptionName] = &[
105 ProgressTopic,
106 ProgressTopicReplicationFactor,
107 PublicKey1,
109 PublicKey2,
110];
111
112pub(crate) const MUTUALLY_EXCLUSIVE_SETS: &[&[ConnectionOptionName]] = &[&[Broker, Brokers]];
114
115pub(super) fn validate_options_per_connection_type(
116 t: CreateConnectionType,
117 mut options: BTreeSet<ConnectionOptionName>,
118) -> Result<(), PlanError> {
119 use mz_sql_parser::ast::ConnectionOptionName::*;
120 let permitted_options = match t {
121 CreateConnectionType::Aws => [
122 AccessKeyId,
123 SecretAccessKey,
124 SessionToken,
125 Endpoint,
126 Region,
127 AssumeRoleArn,
128 AssumeRoleSessionName,
129 ]
130 .as_slice(),
131 CreateConnectionType::AwsPrivatelink => &[AvailabilityZones, Port, ServiceName],
132 CreateConnectionType::GlueSchemaRegistry => &[AwsConnection, Registry],
133 CreateConnectionType::Gcp => &[ServiceAccountKey],
134 CreateConnectionType::Csr => &[
135 AwsPrivatelink,
136 Password,
137 Port,
138 SshTunnel,
139 SslCertificate,
140 SslCertificateAuthority,
141 SslKey,
142 Url,
143 User,
144 ],
145 CreateConnectionType::Kafka => &[
146 AwsConnection,
147 Broker,
148 Brokers,
149 ProgressTopic,
150 ProgressTopicReplicationFactor,
151 AwsPrivatelink,
152 SshTunnel,
153 SslKey,
154 SslCertificate,
155 SslCertificateAuthority,
156 SaslMechanisms,
157 SaslUsername,
158 SaslPassword,
159 SecurityProtocol,
160 ],
161 CreateConnectionType::Postgres => &[
162 AwsConnection,
163 AwsPrivatelink,
164 Database,
165 Host,
166 Password,
167 Port,
168 SshTunnel,
169 SslCertificate,
170 SslCertificateAuthority,
171 SslKey,
172 SslMode,
173 User,
174 ],
175 CreateConnectionType::Ssh => &[Host, Port, User, PublicKey1, PublicKey2],
176 CreateConnectionType::MySql => &[
177 AwsPrivatelink,
178 Host,
179 Password,
180 Port,
181 SshTunnel,
182 SslCertificate,
183 SslCertificateAuthority,
184 SslKey,
185 SslMode,
186 User,
187 AwsConnection,
188 ],
189 CreateConnectionType::SqlServer => &[
190 AwsPrivatelink,
191 Database,
192 Host,
193 Password,
194 Port,
195 SshTunnel,
196 SslCertificate,
197 SslCertificateAuthority,
198 SslKey,
199 SslMode,
200 User,
201 ],
202 CreateConnectionType::IcebergCatalog => &[
203 AccessDelegation,
204 AwsConnection,
205 CatalogType,
206 Credential,
207 GcpConnection,
208 Oauth2ServerUrl,
209 Scope,
210 StorageProvider,
211 Url,
212 Warehouse,
213 ],
214 };
215
216 for o in permitted_options {
217 options.remove(o);
218 }
219
220 if !options.is_empty() {
221 sql_bail!(
222 "{} connections do not support {} values",
223 t,
224 options.iter().join(", ")
225 )
226 }
227
228 Ok(())
229}
230
231impl ConnectionOptionExtracted {
232 pub(super) fn ensure_only_valid_options(
233 &self,
234 t: CreateConnectionType,
235 ) -> Result<(), PlanError> {
236 validate_options_per_connection_type(t, self.seen.clone())
237 }
238
239 pub fn try_into_connection_details(
240 self,
241 scx: &StatementContext,
242 connection_type: CreateConnectionType,
243 ) -> Result<ConnectionDetails, PlanError> {
244 self.ensure_only_valid_options(connection_type)?;
245
246 let connection: ConnectionDetails = match connection_type {
247 CreateConnectionType::Aws => {
248 let credentials = match (
249 self.access_key_id,
250 self.secret_access_key,
251 self.session_token,
252 ) {
253 (Some(access_key_id), Some(secret_access_key), session_token) => {
254 Some(AwsCredentials {
255 access_key_id,
256 secret_access_key: secret_access_key.into(),
257 session_token,
258 })
259 }
260 (None, None, None) => None,
261 _ => {
262 sql_bail!(
263 "must specify both ACCESS KEY ID and SECRET ACCESS KEY with optional SESSION TOKEN"
264 );
265 }
266 };
267
268 let assume_role = match (self.assume_role_arn, self.assume_role_session_name) {
269 (Some(arn), session_name) => Some(AwsAssumeRole { arn, session_name }),
270 (None, Some(_)) => {
271 sql_bail!(
272 "must specify ASSUME ROLE ARN with optional ASSUME ROLE SESSION NAME"
273 );
274 }
275 _ => None,
276 };
277
278 let auth = match (credentials, assume_role) {
279 (None, None) => sql_bail!(
280 "must specify either ASSUME ROLE ARN or ACCESS KEY ID and SECRET ACCESS KEY"
281 ),
282 (Some(credentials), None) => AwsAuth::Credentials(credentials),
283 (None, Some(assume_role)) => AwsAuth::AssumeRole(assume_role),
284 (Some(_), Some(_)) => {
285 sql_bail!("cannot specify both ACCESS KEY ID and ASSUME ROLE ARN");
286 }
287 };
288
289 ConnectionDetails::Aws(AwsConnection {
290 auth,
291 endpoint: match self.endpoint {
292 Some(endpoint) if !endpoint.is_empty() => Some(endpoint),
297 _ => None,
298 },
299 region: self.region,
300 })
301 }
302 CreateConnectionType::AwsPrivatelink => {
303 let connection = AwsPrivatelinkConnection {
304 service_name: self
305 .service_name
306 .ok_or_else(|| sql_err!("SERVICE NAME option is required"))?,
307 availability_zones: self
308 .availability_zones
309 .ok_or_else(|| sql_err!("AVAILABILITY ZONES option is required"))?,
310 };
311 if let Some(supported_azs) = scx.catalog.aws_privatelink_availability_zones() {
312 let mut unique_azs: BTreeSet<String> = BTreeSet::new();
313 let mut duplicate_azs: BTreeSet<String> = BTreeSet::new();
314 for connection_az in &connection.availability_zones {
316 if unique_azs.contains(connection_az) {
317 duplicate_azs.insert(connection_az.to_string());
318 } else {
319 unique_azs.insert(connection_az.to_string());
320 }
321 if !supported_azs.contains(connection_az) {
322 return Err(PlanError::InvalidPrivatelinkAvailabilityZone {
323 name: connection_az.to_string(),
324 supported_azs,
325 });
326 }
327 }
328 if duplicate_azs.len() > 0 {
329 return Err(PlanError::DuplicatePrivatelinkAvailabilityZone {
330 duplicate_azs,
331 });
332 }
333 }
334 ConnectionDetails::AwsPrivatelink(connection)
335 }
336 CreateConnectionType::Gcp => {
337 let credentials_json = self
338 .service_account_key
339 .ok_or_else(|| sql_err!("SERVICE ACCOUNT KEY option is required"))?
340 .into();
341 ConnectionDetails::Gcp(GcpConnection { credentials_json })
342 }
343 CreateConnectionType::Kafka => {
344 let (tls, sasl) = plan_kafka_security(scx, &self)?;
345 let (static_brokers, matching_rules) = self.get_brokers_and_rules(scx)?;
346
347 if !matching_rules.is_empty() {
348 scx.require_feature_flag(&vars::ENABLE_KAFKA_BROKER_MATCHING_RULES)?;
349 }
350
351 ConnectionDetails::Kafka(KafkaConnection {
352 brokers: static_brokers,
353 default_tunnel: build_tunnel_definition(
354 scx,
355 self.ssh_tunnel,
356 self.aws_privatelink,
357 if matching_rules.is_empty() { None } else { Some(matching_rules) },
358 )?,
359 progress_topic: self.progress_topic,
360 progress_topic_options: KafkaTopicOptions {
361 partition_count: Some(NonNeg::try_from(1).expect("1 is positive")),
365 replication_factor: self.progress_topic_replication_factor.map(|val| {
366 if val <= 0 {
367 Err(sql_err!("invalid CONNECTION: PROGRESS TOPIC REPLICATION FACTOR must be greater than 0"))?
368 }
369 NonNeg::try_from(val).map_err(|e| sql_err!("{e}"))
370 }).transpose()?,
371 topic_config: btreemap! {
372 "cleanup.policy".to_string() => "compact".to_string(),
373 "segment.bytes".to_string() => "134217728".to_string(), },
375 },
376 options: BTreeMap::new(),
377 tls,
378 sasl,
379 })
380 }
381 CreateConnectionType::Csr => {
382 let url: reqwest::Url = match self.url {
383 Some(url) => url
384 .parse()
385 .map_err(|e| sql_err!("parsing schema registry url: {e}"))?,
386 None => sql_bail!("invalid CONNECTION: must specify URL"),
387 };
388 let _ = url
389 .host_str()
390 .ok_or_else(|| sql_err!("invalid CONNECTION: URL must specify domain name"))?;
391 if url.path() != "/" {
392 sql_bail!("invalid CONNECTION: URL must have an empty path");
393 }
394 let cert = self.ssl_certificate;
395 let key = self.ssl_key.map(|secret| secret.into());
396 let tls_identity = match (cert, key) {
397 (None, None) => None,
398 (Some(cert), Some(key)) => Some(TlsIdentity { cert, key }),
399 _ => sql_bail!(
400 "invalid CONNECTION: reading from SSL-auth Confluent Schema Registry requires both SSL KEY and SSL CERTIFICATE"
401 ),
402 };
403 let http_auth = self.user.map(|username| CsrConnectionHttpAuth {
404 username,
405 password: self.password.map(|secret| secret.into()),
406 });
407
408 if let Some(privatelink) = self.aws_privatelink.as_ref() {
410 if privatelink.port.is_some() {
411 sql_bail!(
412 "invalid CONNECTION: CONFLUENT SCHEMA REGISTRY does not support PORT for AWS PRIVATELINK"
413 )
414 }
415 }
416 let tunnel = build_tunnel_definition(
417 scx,
418 self.ssh_tunnel,
419 self.aws_privatelink,
420 None, )?;
422
423 ConnectionDetails::Csr(CsrConnection {
424 url,
425 tls_root_cert: self.ssl_certificate_authority,
426 tls_identity,
427 http_auth,
428 tunnel,
429 })
430 }
431 CreateConnectionType::GlueSchemaRegistry => {
432 let aws_connection = get_aws_connection_reference(scx, &self)?
433 .ok_or_else(|| sql_err!("AWS CONNECTION option is required"))?;
434 let registry_name = self
435 .registry
436 .ok_or_else(|| sql_err!("REGISTRY option is required"))?;
437 if registry_name.is_empty() {
438 sql_bail!("invalid CONNECTION: REGISTRY must not be empty");
439 }
440
441 ConnectionDetails::GlueSchemaRegistry(GlueSchemaRegistryConnection {
442 aws_connection,
443 registry_name,
444 })
445 }
446 CreateConnectionType::Postgres => {
447 let aws_connection = get_aws_connection_reference(scx, &self)?;
448 if aws_connection.is_some() && self.password.is_some() {
449 sql_bail!(
450 "invalid CONNECTION: AWS IAM authentication is not supported with password"
451 );
452 }
453
454 let cert = self.ssl_certificate;
455 let key = self.ssl_key.map(|secret| secret.into());
456 let tls_identity = match (cert, key) {
457 (None, None) => None,
458 (Some(cert), Some(key)) => Some(TlsIdentity { cert, key }),
459 _ => sql_bail!(
460 "invalid CONNECTION: both SSL KEY and SSL CERTIFICATE are required"
461 ),
462 };
463 let tls_mode = match self.ssl_mode.as_ref().map(|m| m.as_str()) {
464 None | Some("disable") => {
465 if aws_connection.is_some() {
468 sql_bail!(
469 "invalid CONNECTION: AWS IAM authentication requires SSL to be enabled"
470 )
471 }
472 tokio_postgres::config::SslMode::Disable
473 }
474 Some("require") | Some("required") => tokio_postgres::config::SslMode::Require,
477 Some("verify_ca") | Some("verify-ca") => {
478 tokio_postgres::config::SslMode::VerifyCa
479 }
480 Some("verify_full") | Some("verify-full") => {
481 tokio_postgres::config::SslMode::VerifyFull
482 }
483 Some(m) => sql_bail!("invalid CONNECTION: unknown SSL MODE {}", m.quoted()),
484 };
485
486 if let Some(privatelink) = self.aws_privatelink.as_ref() {
488 if privatelink.port.is_some() {
489 sql_bail!(
490 "invalid CONNECTION: POSTGRES does not support PORT for AWS PRIVATELINK"
491 )
492 }
493 }
494 let tunnel = build_tunnel_definition(
495 scx,
496 self.ssh_tunnel,
497 self.aws_privatelink,
498 None, )?;
500
501 ConnectionDetails::Postgres(PostgresConnection {
502 database: self
503 .database
504 .ok_or_else(|| sql_err!("DATABASE option is required"))?,
505 password: self.password.map(|password| password.into()),
506 host: self
507 .host
508 .ok_or_else(|| sql_err!("HOST option is required"))?,
509 port: self.port.unwrap_or(5432_u16),
510 tunnel,
511 tls_mode,
512 tls_root_cert: self.ssl_certificate_authority,
513 tls_identity,
514 user: self
515 .user
516 .ok_or_else(|| sql_err!("USER option is required"))?,
517 aws_connection,
518 })
519 }
520 CreateConnectionType::Ssh => {
521 let ensure_key = |public_key| match public_key {
522 Some(public_key) => Ok::<_, anyhow::Error>(SshKey::PublicOnly(public_key)),
523 None => {
524 let key = SshKeyPair::new().context("creating SSH key")?;
525 Ok(SshKey::Both(key))
526 }
527 };
528 ConnectionDetails::Ssh {
529 connection: SshConnection {
530 host: self
531 .host
532 .ok_or_else(|| sql_err!("HOST option is required"))?,
533 port: self.port.unwrap_or(22_u16),
534 user: match self
535 .user
536 .ok_or_else(|| sql_err!("USER option is required"))?
537 {
538 StringOrSecret::String(user) => user,
539 StringOrSecret::Secret(_) => {
540 sql_bail!(
541 "SSH connections do not support supplying USER value as SECRET"
542 )
543 }
544 },
545 },
546 key_1: ensure_key(self.public_key1)?,
547 key_2: ensure_key(self.public_key2)?,
548 }
549 }
550 CreateConnectionType::MySql => {
551 let aws_connection = get_aws_connection_reference(scx, &self)?;
552 if aws_connection.is_some() && self.password.is_some() {
553 sql_bail!(
554 "invalid CONNECTION: AWS IAM authentication is not supported with password"
555 );
556 }
557
558 let cert = self.ssl_certificate;
559 let key = self.ssl_key.map(|secret| secret.into());
560 let tls_identity = match (cert, key) {
561 (None, None) => None,
562 (Some(cert), Some(key)) => Some(TlsIdentity { cert, key }),
563 _ => sql_bail!(
564 "invalid CONNECTION: both SSL KEY and SSL CERTIFICATE are required"
565 ),
566 };
567 let tls_mode = match self
570 .ssl_mode
571 .map(|f| f.to_uppercase())
572 .as_ref()
573 .map(|m| m.as_str())
574 {
575 None | Some("DISABLED") => {
576 if aws_connection.is_some() {
577 sql_bail!(
578 "invalid CONNECTION: AWS IAM authentication requires SSL to be enabled"
579 )
580 }
581 MySqlSslMode::Disabled
582 }
583 Some("REQUIRED") | Some("REQUIRE") => MySqlSslMode::Required,
586 Some("VERIFY_CA") | Some("VERIFY-CA") => MySqlSslMode::VerifyCa,
587 Some("VERIFY_IDENTITY") | Some("VERIFY-IDENTITY") => {
588 MySqlSslMode::VerifyIdentity
589 }
590 Some(m) => sql_bail!("invalid CONNECTION: unknown SSL MODE {}", m.quoted()),
591 };
592
593 if let Some(privatelink) = self.aws_privatelink.as_ref() {
595 if privatelink.port.is_some() {
596 sql_bail!(
597 "invalid CONNECTION: MYSQL does not support PORT for AWS PRIVATELINK"
598 )
599 }
600 }
601 let tunnel = build_tunnel_definition(
602 scx,
603 self.ssh_tunnel,
604 self.aws_privatelink,
605 None, )?;
607
608 ConnectionDetails::MySql(MySqlConnection {
609 password: self.password.map(|password| password.into()),
610 host: self
611 .host
612 .ok_or_else(|| sql_err!("HOST option is required"))?,
613 port: self.port.unwrap_or(3306_u16),
614 tunnel,
615 tls_mode,
616 tls_root_cert: self.ssl_certificate_authority,
617 tls_identity,
618 user: self
619 .user
620 .ok_or_else(|| sql_err!("USER option is required"))?,
621 aws_connection,
622 })
623 }
624 CreateConnectionType::SqlServer => {
625 let aws_connection = get_aws_connection_reference(scx, &self)?;
626 if aws_connection.is_some() && self.password.is_some() {
627 sql_bail!(
628 "invalid CONNECTION: AWS IAM authentication is not supported with password"
629 );
630 }
631
632 let (encryption, certificate_validation_policy) = match self
633 .ssl_mode
634 .map(|mode| mode.to_uppercase())
635 .as_ref()
636 .map(|mode| mode.as_str())
637 {
638 None | Some("DISABLED") => (
639 mz_sql_server_util::config::EncryptionLevel::None,
640 mz_sql_server_util::config::CertificateValidationPolicy::TrustAll,
641 ),
642 Some("REQUIRED") => (
643 mz_sql_server_util::config::EncryptionLevel::Required,
644 mz_sql_server_util::config::CertificateValidationPolicy::TrustAll,
645 ),
646 Some("VERIFY") => (
647 mz_sql_server_util::config::EncryptionLevel::Required,
648 mz_sql_server_util::config::CertificateValidationPolicy::VerifySystem,
649 ),
650 Some("VERIFY_CA") => {
651 if self.ssl_certificate_authority.is_none() {
652 sql_bail!(
653 "invalid CONNECTION: SSL MODE 'verify_ca' requires SSL CERTIFICATE AUTHORITY"
654 );
655 }
656 (
657 mz_sql_server_util::config::EncryptionLevel::Required,
658 mz_sql_server_util::config::CertificateValidationPolicy::VerifyCA,
659 )
660 }
661 Some(mode) => {
662 sql_bail!("invalid CONNECTION: unknown SSL MODE {}", mode.quoted())
663 }
664 };
665
666 if let Some(privatelink) = self.aws_privatelink.as_ref() {
667 if privatelink.port.is_some() {
668 sql_bail!(
669 "invalid CONNECTION: SQL SERVER does not support PORT for AWS PRIVATELINK"
670 )
671 }
672 }
673
674 let port = self.port.unwrap_or(1433_u16);
678 let tunnel = build_tunnel_definition(
679 scx,
680 self.ssh_tunnel,
681 self.aws_privatelink,
682 None, )?;
684
685 ConnectionDetails::SqlServer(SqlServerConnectionDetails {
686 host: self
687 .host
688 .ok_or_else(|| sql_err!("HOST option is required"))?,
689 port,
690 database: self
691 .database
692 .ok_or_else(|| sql_err!("DATABASE option is required"))?,
693 user: self
694 .user
695 .ok_or_else(|| sql_err!("USER option is required"))?,
696 password: self
697 .password
698 .ok_or_else(|| sql_err!("PASSWORD option is required"))
699 .map(|pass| pass.into())?,
700 tunnel,
701 encryption,
702 certificate_validation_policy,
703 tls_root_cert: self.ssl_certificate_authority,
704 })
705 }
706 CreateConnectionType::IcebergCatalog => {
707 let catalog_type = self.catalog_type.clone().ok_or_else(|| {
708 sql_err!("invalid CONNECTION: ICEBERG connections must specify CATALOG TYPE")
709 })?;
710
711 let uri: reqwest::Url = match &self.url {
712 Some(url) => url
713 .parse()
714 .map_err(|e| sql_err!("parsing Iceberg catalog url: {e}"))?,
715 None => sql_bail!("invalid CONNECTION: must specify URL"),
716 };
717
718 let warehouse = self.warehouse.clone();
719 let credential = self.credential.clone();
720 let aws_connection = get_aws_connection_reference(scx, &self)?;
721 let gcp_connection = get_gcp_connection_reference(scx, &self)?;
722
723 let catalog = match catalog_type {
724 IcebergCatalogType::S3TablesRest => {
725 if gcp_connection.is_some() {
726 sql_bail!(
727 "invalid CONNECTION: ICEBERG s3tablesrest connections do not support GCP CONNECTION"
728 );
729 }
730 if self.oauth2_server_url.is_some() {
731 sql_bail!(
732 "invalid CONNECTION: ICEBERG s3tablesrest connections do not support OAUTH2 SERVER URL"
733 );
734 }
735 if self.access_delegation.is_some() {
736 sql_bail!(
737 "invalid CONNECTION: ICEBERG s3tablesrest connections do not support ACCESS DELEGATION"
738 );
739 }
740 if self.storage_provider.is_some() {
741 sql_bail!(
742 "invalid CONNECTION: ICEBERG s3tablesrest connections do not support STORAGE PROVIDER"
743 );
744 }
745 let Some(warehouse) = warehouse else {
746 sql_bail!(
747 "invalid CONNECTION: ICEBERG s3tablesrest connections must specify WAREHOUSE"
748 );
749 };
750 let Some(aws_connection) = aws_connection else {
751 sql_bail!(
752 "invalid CONNECTION: ICEBERG s3tablesrest connections require an AWS connection"
753 );
754 };
755
756 IcebergCatalogImpl::S3TablesRest(S3TablesRestIcebergCatalog {
757 aws_connection,
758 warehouse,
759 })
760 }
761 IcebergCatalogType::Rest => {
762 if aws_connection.is_some() {
763 sql_bail!(
764 "invalid CONNECTION: ICEBERG rest connections do not support AWS CONNECTION.\n\nTry s3tablesrest instead."
765 );
766 }
767 let auth = match (credential, gcp_connection) {
768 (Some(_), Some(_)) => sql_bail!(
769 "invalid CONNECTION: ICEBERG rest connections may set CREDENTIAL or GCP CONNECTION, not both"
770 ),
771 (Some(credential), None) => IcebergCatalogAuth::OAuth {
772 credential,
773 scope: self.scope.clone(),
774 server_url: self.oauth2_server_url.clone(),
775 },
776 (None, Some(gcp_connection)) => {
777 if self.oauth2_server_url.is_some() {
778 sql_bail!(
779 "invalid CONNECTION: OAUTH2 SERVER URL applies to CREDENTIAL auth, not GCP CONNECTION"
780 );
781 }
782 if let Some(provider) = self.storage_provider
787 && provider != IcebergStorageProvider::Gcs
788 {
789 sql_bail!(
790 "invalid CONNECTION: ICEBERG GCP CONNECTION implies STORAGE PROVIDER 'gcs', not '{}'",
791 provider.as_str()
792 );
793 }
794 const BIGLAKE_CATALOG_URI: &str =
796 "https://biglake.googleapis.com/iceberg/v1/restcatalog";
797 if uri.to_string() != BIGLAKE_CATALOG_URI {
798 sql_bail!(
799 "GCP connection can only be used with '{}'",
800 BIGLAKE_CATALOG_URI
801 );
802 }
803 IcebergCatalogAuth::Gcp(gcp_connection)
804 }
805 (None, None) => sql_bail!(
806 "invalid CONNECTION: ICEBERG rest connections require a CREDENTIAL or GCP CONNECTION"
807 ),
808 };
809
810 let storage_provider = if matches!(auth, IcebergCatalogAuth::Gcp(_)) {
813 IcebergStorageProvider::Gcs
814 } else {
815 self.storage_provider.unwrap_or_default()
816 };
817
818 IcebergCatalogImpl::Rest(RestIcebergCatalog {
819 auth,
820 warehouse,
821 access_delegation: self.access_delegation,
822 storage_provider,
823 })
824 }
825 };
826
827 ConnectionDetails::IcebergCatalog(IcebergCatalogConnection { catalog, uri })
828 }
829 };
830
831 Ok(connection)
832 }
833
834 pub fn get_brokers_and_rules(
835 &self,
836 scx: &StatementContext,
837 ) -> Result<
838 (
839 Vec<mz_storage_types::connections::KafkaBroker<ReferencedConnection>>,
840 Vec<KafkaMatchingBrokerRule<Aug>>,
841 ),
842 PlanError,
843 > {
844 let mut all_brokers: Vec<KafkaBroker<Aug>> = vec![];
846 let mut matching_rules: Vec<KafkaMatchingBrokerRule<Aug>> = vec![];
847
848 match (&self.broker, &self.brokers, &self.aws_privatelink) {
850 (Some(broker), None, None) => all_brokers.extend(broker.iter().cloned()),
852 (None, Some(broker_list), None) => {
854 all_brokers.extend(broker_list.static_entries.iter().cloned());
855 matching_rules.extend(broker_list.matching_rules.iter().cloned());
856 }
857 (None, None, Some(_privatelink)) => {
859 }
861 (None, None, None) => {
863 sql_bail!("invalid CONNECTION: must set one of BROKER, BROKERS, or AWS PRIVATELINK")
864 }
865 _ => sql_bail!(
867 "invalid CONNECTION: can only set one of BROKER, BROKERS, or AWS PRIVATELINK"
868 ),
869 };
870
871 if !matching_rules.is_empty() && all_brokers.is_empty() {
873 sql_bail!(
874 "invalid CONNECTION: BROKERS must contain at least one static broker address"
875 );
876 }
877
878 let mut out = vec![];
881 for broker in &all_brokers {
882 if broker.address.contains(',') {
883 sql_bail!(
884 "invalid CONNECTION: cannot specify multiple Kafka broker addresses in one string.\n\nInstead, specify BROKERS using multiple strings, e.g. BROKERS ('kafka:9092', 'kafka:9093')"
885 );
886 }
887
888 let tunnel = match &broker.tunnel {
889 KafkaBrokerTunnel::Direct => Tunnel::Direct,
890 KafkaBrokerTunnel::AwsPrivatelink(aws_privatelink) => {
891 Tunnel::AwsPrivatelink(plan_privatelink(scx, aws_privatelink)?)
892 }
893 KafkaBrokerTunnel::SshTunnel(ssh) => {
894 let id = match &ssh {
895 ResolvedItemName::Item { id, .. } => id,
896 _ => sql_bail!(
897 "internal error: Kafka SSH tunnel connection was not resolved"
898 ),
899 };
900 let ssh_tunnel = scx.catalog.get_item(id);
901 match ssh_tunnel.connection()? {
902 Connection::Ssh(_connection) => Tunnel::Ssh(SshTunnel {
903 connection_id: *id,
904 connection: *id,
905 }),
906 _ => {
907 sql_bail!("{} is not an SSH connection", ssh_tunnel.name().item)
908 }
909 }
910 }
911 };
912
913 out.push(mz_storage_types::connections::KafkaBroker {
914 address: broker.address.clone(),
915 tunnel,
916 });
917 }
918
919 Ok((out, matching_rules))
920 }
921}
922
923fn get_aws_connection_reference(
924 scx: &StatementContext,
925 conn_options: &ConnectionOptionExtracted,
926) -> Result<Option<AwsConnectionReference<ReferencedConnection>>, PlanError> {
927 let Some(aws_connection_id) = conn_options.aws_connection else {
928 return Ok(None);
929 };
930
931 let id = CatalogItemId::from(aws_connection_id);
932 let item = scx.catalog.get_item(&id);
933 Ok(match item.connection()? {
934 Connection::Aws(_) => Some(AwsConnectionReference {
935 connection_id: id,
936 connection: id,
937 }),
938 _ => sql_bail!("{} is not an AWS connection", item.name().item),
939 })
940}
941fn get_gcp_connection_reference(
942 scx: &StatementContext,
943 conn_options: &ConnectionOptionExtracted,
944) -> Result<Option<GcpConnectionReference<ReferencedConnection>>, PlanError> {
945 let Some(gcp_connection_id) = conn_options.gcp_connection else {
946 return Ok(None);
947 };
948
949 let id = CatalogItemId::from(gcp_connection_id);
950 let item = scx.catalog.get_item(&id);
951 Ok(match item.connection()? {
952 Connection::Gcp(_) => Some(GcpConnectionReference {
953 connection_id: id,
954 connection: id,
955 }),
956 _ => sql_bail!("{} is not a GCP connection", item.name().item),
957 })
958}
959
960fn plan_kafka_security(
961 scx: &StatementContext,
962 v: &ConnectionOptionExtracted,
963) -> Result<
964 (
965 Option<KafkaTlsConfig>,
966 Option<KafkaSaslConfig<ReferencedConnection>>,
967 ),
968 PlanError,
969> {
970 const SASL_CONFIGS: [ConnectionOptionName; 4] = [
971 ConnectionOptionName::AwsConnection,
972 ConnectionOptionName::SaslMechanisms,
973 ConnectionOptionName::SaslUsername,
974 ConnectionOptionName::SaslPassword,
975 ];
976
977 const ALL_CONFIGS: [ConnectionOptionName; 7] = concat_arrays!(
978 [
979 ConnectionOptionName::SslKey,
980 ConnectionOptionName::SslCertificate,
981 ConnectionOptionName::SslCertificateAuthority,
982 ],
983 SASL_CONFIGS
984 );
985
986 enum SecurityProtocol {
987 Plaintext,
988 Ssl,
989 SaslPlaintext,
990 SaslSsl,
991 }
992
993 let security_protocol = v.security_protocol.as_ref().map(|v| v.to_uppercase());
994 let security_protocol = match security_protocol.as_deref() {
995 Some("PLAINTEXT") => SecurityProtocol::Plaintext,
996 Some("SSL") => SecurityProtocol::Ssl,
997 Some("SASL_PLAINTEXT") => SecurityProtocol::SaslPlaintext,
998 Some("SASL_SSL") => SecurityProtocol::SaslSsl,
999 Some(p) => sql_bail!("unknown security protocol: {}", p),
1000 None if SASL_CONFIGS.iter().any(|c| v.seen.contains(c)) => SecurityProtocol::SaslSsl,
1005 None => SecurityProtocol::Ssl,
1006 };
1007
1008 let mut outstanding = ALL_CONFIGS
1009 .into_iter()
1010 .filter(|c| v.seen.contains(c))
1011 .collect::<BTreeSet<ConnectionOptionName>>();
1012
1013 let tls = match security_protocol {
1014 SecurityProtocol::Ssl | SecurityProtocol::SaslSsl => {
1015 outstanding.remove(&ConnectionOptionName::SslCertificate);
1016 let identity = match &v.ssl_certificate {
1017 None => None,
1018 Some(cert) => {
1019 outstanding.remove(&ConnectionOptionName::SslKey);
1020 let Some(key) = &v.ssl_key else {
1021 sql_bail!("SSL KEY must be specified with SSL CERTIFICATE");
1022 };
1023 Some(TlsIdentity {
1024 cert: cert.clone(),
1025 key: (*key).into(),
1026 })
1027 }
1028 };
1029 outstanding.remove(&ConnectionOptionName::SslCertificateAuthority);
1030 Some(KafkaTlsConfig {
1031 identity,
1032 root_cert: v.ssl_certificate_authority.clone(),
1033 })
1034 }
1035 _ => None,
1036 };
1037
1038 let sasl = match security_protocol {
1039 SecurityProtocol::SaslPlaintext | SecurityProtocol::SaslSsl => {
1040 outstanding.remove(&ConnectionOptionName::AwsConnection);
1041 match get_aws_connection_reference(scx, v)? {
1042 Some(aws) => Some(KafkaSaslConfig {
1043 mechanism: "OAUTHBEARER".into(),
1044 username: "".into(),
1045 password: None,
1046 aws: Some(aws),
1047 }),
1048 None => {
1049 outstanding.remove(&ConnectionOptionName::SaslMechanisms);
1050 outstanding.remove(&ConnectionOptionName::SaslUsername);
1051 outstanding.remove(&ConnectionOptionName::SaslPassword);
1052 let Some(mechanism) = &v.sasl_mechanisms else {
1055 sql_bail!("SASL MECHANISMS must be specified");
1056 };
1057 let Some(username) = &v.sasl_username else {
1058 sql_bail!("SASL USERNAME must be specified");
1059 };
1060 let Some(password) = &v.sasl_password else {
1061 sql_bail!("SASL PASSWORD must be specified");
1062 };
1063 Some(KafkaSaslConfig {
1064 mechanism: mechanism.to_uppercase(),
1075 username: username.clone(),
1076 password: Some((*password).into()),
1077 aws: None,
1078 })
1079 }
1080 }
1081 }
1082 _ => None,
1083 };
1084
1085 if let Some(outstanding) = outstanding.first() {
1086 sql_bail!("option {outstanding} not supported with this configuration");
1087 }
1088
1089 Ok((tls, sasl))
1090}
1091pub fn plan_default_privatelink(
1092 scx: &StatementContext,
1093 pl: &mz_sql_parser::ast::ConnectionDefaultAwsPrivatelink<Aug>,
1094) -> Result<AwsPrivatelink, PlanError> {
1095 let id = pl.connection.item_id().clone();
1096 let entry = scx.catalog.get_item(&id);
1097 match entry.connection()? {
1098 Connection::AwsPrivatelink(_) => Ok(AwsPrivatelink {
1099 connection_id: id,
1100 availability_zone: None,
1102 port: pl.port,
1104 }),
1105 _ => sql_bail!("{} is not an AWS PRIVATELINK connection", entry.name().item),
1106 }
1107}
1108
1109pub fn plan_privatelink(
1110 scx: &StatementContext,
1111 pl: &mz_sql_parser::ast::KafkaBrokerAwsPrivatelink<Aug>,
1112) -> Result<AwsPrivatelink, PlanError> {
1113 let KafkaBrokerAwsPrivatelinkOptionExtracted {
1114 availability_zone,
1115 port,
1116 seen: _,
1117 } = KafkaBrokerAwsPrivatelinkOptionExtracted::try_from(pl.options.clone())?;
1118
1119 let id = match &pl.connection {
1120 ResolvedItemName::Item { id, .. } => id,
1121 _ => sql_bail!("internal error: Kafka PrivateLink connection was not resolved"),
1122 };
1123 let entry = scx.catalog.get_item(id);
1124 match entry.connection()? {
1125 Connection::AwsPrivatelink(connection) => {
1126 if let Some(az) = &availability_zone {
1127 if !connection.availability_zones.contains(az) {
1128 sql_bail!(
1129 "AWS PrivateLink availability zone {} does not match any of the \
1130 availability zones on the AWS PrivateLink connection {}",
1131 az.quoted(),
1132 scx.catalog
1133 .resolve_full_name(entry.name())
1134 .to_string()
1135 .quoted()
1136 )
1137 }
1138 }
1139 Ok(AwsPrivatelink {
1140 connection_id: *id,
1141 availability_zone,
1142 port,
1143 })
1144 }
1145 _ => {
1146 sql_bail!("{} is not an AWS PRIVATELINK connection", entry.name().item)
1147 }
1148 }
1149}
1150
1151pub(crate) fn build_tunnel_definition(
1152 scx: &StatementContext,
1153 ssh_tunnel: Option<with_options::Object>,
1154 aws_privatelink: Option<ConnectionDefaultAwsPrivatelink<Aug>>,
1155 matching_rules: Option<Vec<KafkaMatchingBrokerRule<Aug>>>,
1156) -> Result<Tunnel<ReferencedConnection>, PlanError> {
1157 Ok(match (ssh_tunnel, aws_privatelink, matching_rules) {
1158 (None, None, None) => Tunnel::Direct,
1159 (Some(ssh_tunnel), None, None) => {
1160 let id = CatalogItemId::from(ssh_tunnel);
1161 let ssh_tunnel = scx.catalog.get_item(&id);
1162 match ssh_tunnel.connection()? {
1163 Connection::Ssh(_connection) => Tunnel::Ssh(SshTunnel {
1164 connection_id: id,
1165 connection: id,
1166 }),
1167 _ => sql_bail!("{} is not an SSH connection", ssh_tunnel.name().item),
1168 }
1169 }
1170 (None, Some(aws_privatelink), None) => {
1171 Tunnel::AwsPrivatelink(plan_default_privatelink(scx, &aws_privatelink)?)
1172 }
1173 (None, None, Some(rules)) => {
1174 if rules.is_empty() {
1175 sql_bail!("BROKERS MATCHING rules list cannot be empty");
1176 }
1177
1178 let rules = rules
1179 .iter()
1180 .map(|rule| {
1181 Ok(AwsPrivatelinkRule {
1182 pattern: rule.pattern.clone(),
1183 to: plan_privatelink(scx, &rule.tunnel)?,
1184 })
1185 })
1186 .collect::<Result<Vec<_>, PlanError>>()?;
1187 Tunnel::AwsPrivatelinks(mz_storage_types::connections::AwsPrivatelinks { rules })
1188 }
1189 _ => {
1190 sql_bail!("cannot specify both SSH TUNNEL and AWS PRIVATELINK");
1191 }
1192 })
1193}